【发布时间】:2021-02-11 18:16:09
【问题描述】:
我在 Typescript 中遇到了一些关于数组缩减的问题。 为简化起见,假设我有一个简单的数字数组,我想在其中删除重复项并返回一个没有它们的新数组,我曾经使用 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 累加器应该是一个数字数组,有什么解决方案吗?
【问题讨论】:
-
尝试使用数组构造函数
const new: number[] = nums.reduce((acc: number[], item:number) => acc.includes(item) ? acc : [...acc, item], new Array<number>()); -
我在 TS 游乐场Playground Link 上没有看到问题
标签: arrays typescript reduce