微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决数组减少无法正确推断类型

我在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,[])

我收到“新”错误

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

以及累加器上的错误

TS2769: No overload matches this call.

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

解决方法

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

,

根据减少功能类型:

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,[])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。