【问题标题】:array reduce not correctly inferring types数组减少不能正确推断类型
【发布时间】: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


【解决方案1】:

这样做nums.reduce<number[]>(...) 告诉 TypeScript reduce 将返回什么

【讨论】:

    【解决方案2】:

    根据函数类型减少:

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

    【讨论】:

    • 谢谢,我错过了
    猜你喜欢
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多