我有一个简单的例子,如
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我们怎样才能解决这个问题?由于
为了修复这个错误,您需要在reduce
函数上添加type。可以通过调用
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[])
但是我觉得第一个看起来更好。
你可以在这里找到一个工作的例子
我试试别的办法
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)