Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda