数组减少无法正确推断类型

时间:2020-10-29 10:01:36

标签: arrays typescript reduce

我在Typescript中遇到数组减少的麻烦。 为简化起见,假设我有一个简单的数字数组,我想删除重复项并返回没有它们的新数组,我习惯使用reduce来做类似的事情:

const new = nums.reduce((acc, item) => acc.includes(item) ? acc : [...acc, item], [])

其中: nums = [0,0,1,1,1,2,2,3,3,4] 新的应该是: 新= [0,1,2,3,4]

我试图这样输入函数:

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

我收到“新”错误:

TS2322: Type 'number' is not assignable to type 'number[]'.

以及累加器上的错误:

TS2769: No overload matches this call.

似乎没有办法告诉打字稿累加器应该是一个数字数组,有解决方案吗?

2 个答案:

答案 0 :(得分:2)

执行此nums.reduce<number[]>(...)来告诉TypeScript reduce将返回什么

答案 1 :(得分:1)

根据减少功能类型:

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

initialValue推断出返回值。因此,您可以投放initialValue

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

或重写模板参数:

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