0

I'm trying to use async await with reduce function in TypeScript:

const getMyItems = async (items: MyType[]) => {
  return await items.reduce(async (allItems, currItem) => {
    const shouldAddItem = await someCheck(currItem);
    return [...allItems, ...(shouldAddItem ? [currItem] : [])];
  }, []);
};

I get error on this line:

return await items.reduce(async (allItems, currItem) => {
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Error message:

TS2769: No overload matches this call.   Overload 1 of 3,
'(callbackfn: (previousValue: InviteASItemProps, currentValue:
InviteASItemProps, currentIndex: number, array: InviteASItemProps[])
=> InviteASItemProps, initialValue: InviteASItemProps): InviteASItemProps', gave the following error.     Argument of type
'(filteredItems: never[], currentItem: InviteASItemProps) =>
Promise' is not assignable to
parameter of type '(previousValue: InviteASItemProps, currentValue:
InviteASItemProps, currentIndex: number, array: InviteASItemProps[])
=> InviteASItemProps'.       Types of parameters 'filteredItems' and 'previousValue' are incompatible.         Type 'InviteASItemProps' is
missing the following properties from type 'never[]': length, pop,
push, concat, and 29 more.   Overload 2 of 3, '(callbackfn:
(previousValue: never[], currentValue: InviteASItemProps,
currentIndex: number, array: InviteASItemProps[]) => never[],
initialValue: never[]): never[]', gave the following error.
    Argument of type '(filteredItems: never[], currentItem: InviteASItemProps) => Promise' is not
assignable to parameter of type '(previousValue: never[],
currentValue: InviteASItemProps, currentIndex: number, array:
InviteASItemProps[]) => never[]'.       Type
'Promise' is missing the following
properties from type 'never[]': length, pop, push, concat, and 29
more.

Any ideas why?

When I use allItems: any it's fixed.

XouDo
  • 945
  • 10
  • 19
user12499410
  • 392
  • 5
  • 17
  • 1
    This is because the initial value is an ordinary ```Array``` type, but it needs to be a ```Promise``` type. try replace ```[]``` with ```Promise.resolve([])```... – bloo Nov 29 '21 at 07:47
  • did that and added `await` before all uses of accumalator .. still same problem – user12499410 Nov 29 '21 at 07:49

0 Answers0