typescript 如何使用reduce替换打印脚本中的filter和map

y4ekin9u  于 2023-01-21  发布在  TypeScript
关注(0)|答案(2)|浏览(131)

我举个简单的例子

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我们如何修复它?谢谢

flvlnr44

flvlnr441#

为了修复此错误,需要在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[])

但我觉得第一个更好看。
您可以在本练习中找到一个工作示例

xam8gpfp

xam8gpfp2#

我试试别的办法

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

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

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

console.log(data)

相关问题