array reduce not correctly inferring types

According to reduce function types:

reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;

The return value is inferred from the initialValue. So you can either cast initialValue:

nums.reduce((acc, item) => acc.includes(item) ? acc : [...acc, item], [] as number[])

Or rewrite template argument:

nums.reduce<number[]>((acc, item) => acc.includes(item) ? acc : [...acc, item], [])

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top