array reduce 不正确地推断类型
array reduce not correctly inferring types
我在 Typescript 中使用数组减少时遇到了一些问题。
为了简化,假设我有一个简单的数字数组,我想在其中删除重复项和 return 一个没有它们的新数组我曾经使用 reduce:
做这样的事情
const new = nums.reduce((acc, item) => acc.includes(item) ? acc : [...acc, item], [])
其中:
数字 = [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.
似乎没有办法告诉 typescript 累加器应该是一个数字数组,有什么解决方案吗?
执行此操作nums.reduce<number[]>(...)
以告诉 TypeScript 什么会减少 return
根据reduce函数类型:
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
return 值是从 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], [])
我在 Typescript 中使用数组减少时遇到了一些问题。 为了简化,假设我有一个简单的数字数组,我想在其中删除重复项和 return 一个没有它们的新数组我曾经使用 reduce:
做这样的事情const new = nums.reduce((acc, item) => acc.includes(item) ? acc : [...acc, item], [])
其中: 数字 = [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.
似乎没有办法告诉 typescript 累加器应该是一个数字数组,有什么解决方案吗?
执行此操作nums.reduce<number[]>(...)
以告诉 TypeScript 什么会减少 return
根据reduce函数类型:
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
return 值是从 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], [])