Home > database >  Typescript array reduce with async/await showing type mismatch error
Typescript array reduce with async/await showing type mismatch error

Time:02-21

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

CodePudding user response:

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);
    });
  • Related