【问题标题】:How to use reduce to replace filter and map in typescript如何使用reduce替换打字稿中的过滤器和映射
【发布时间】:2021-12-10 08:39:55
【问题描述】:

我有一个简单的例子,比如

    interface employer {
      name: string;
      age: number;
    }

    const arr: employer[] = [{name:'Amy',age:18},{name:'Bob',age:20}];

    let data = arr.reduce((c, b) =>  b.age > 18 ? [...c, b] : c,[])

    console.log(data)

我只想归档 arr 数组并返回此人的年龄高于 18 岁,例如 但我得到错误

No overload matches this call.
  Overload 1 of 3, '(callbackfn: (previousValue: employer, currentValue: employer, currentIndex: number, array: employer[]) => employer, initialValue: employer): employer', gave the following error.
    Type 'employer[]' is missing the following properties from type 'employer': name, age
  Overload 2 of 3, '(callbackfn: (previousValue: never[], currentValue: employer, currentIndex: number, array: employer[]) => never[], initialValue: never[]): never[]', gave the following error.
    Type 'employer[]' is not assignable to type 'never[]'.
      Type 'employer' is not assignable to type 'never'.

为此b.age > 18 ? [...c, b] : c 我认为它适用于javascript 我们该如何解决? 谢谢

【问题讨论】:

    标签: typescript reduce


    【解决方案1】:

    为了修复此错误,您需要在reduce 函数上添加类型。你可以通过调用来做到这一点

    let data = arr.reduce<employer[]>((c, b) =>  b.age > 18 ? [...c, b] : c,[])
    

    另外,这是有效的

    let data = arr.reduce((c, b) =>  b.age > 18 ? [...c, b] : c,[] as employer[])
    

    但我认为第一个看起来更好。

    您可以在 playground 中找到一个工作示例

    【讨论】:

      【解决方案2】:

      我尝试另一种方式

      interface employer { 
            name: string; 
            age: number; 
          } 
       
          const arr: employer[] = [{name:'Amy',age:18},{name:'Bob',age:20}]; 
       
          let data = arr.reduce((c:any, b:any) =>  b.age > 18 ? [...c, b] : c,[]) 
       
          console.log(arr)
      

      【讨论】:

      • 你正在失去类型安全性
      • 你为什么认为这是不正确的@GeorgiosKampitakis?
      • 使用 any 违背了使用类型的目的,如果你这样做 arr.reduce((c:any, b:any) =&gt; b.wrong &gt; 18 ? [...c, b] : c,[]) 这将仍然编译但抛出运行时错误 b.wrong 存在于任何类型中。
      猜你喜欢
      • 2020-01-02
      • 2019-06-03
      • 2018-09-26
      • 2019-07-07
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多