Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
Typescript array reduce with async/await showing type mismatch error

Seem to be having some type issue by using async/await with .reduce()

I have to call one async function inside the reduce with proper types but I can't figure out why Anyone pls help me

interface Person {
  name: string;
  age: number;
}

const persons: Person[] = [
  { name: 'John', age: 30 },
  { name: 'Alice', age: 45 },
];

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

const ageByPerson: Person[] = persons.reduce<Person[]>(
  async (result, person) => {
    await sleep(4000);
    return result.concat({
      age: person.age,
      name: person.name,
    });
  },
  []
);
console.log('age ', ageByPerson);

Without interface is working fine But when I am using with interface I can't figure it out

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Since the callback is async, it'll always return a Promise; the type parameter should not be Person[], but Promise<Person[]>. You also need to pass such a value as the initial value, and wait for the prior accumulator to resolve before concating.

const ageByPersonPromise = persons.reduce<Promise<Person[]>>(
    async (resultPromise, person) => {
        const result = await resultPromise;
        await sleep(4000);
        return result.concat({
            age: person.age,
            name: person.name,
        });
    },
    Promise.resolve([])
);
ageByPersonPromise
    .then((ageByPerson) => {
        console.log('age ', ageByPerson);
    });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda