TypeScript:reduce 函数 - 没有重载与此调用匹配

dna*_*ion 9 arrays typescript

尝试编写一个基本的减速器以从对象数组中返回键(的值)数组。某些键可能丢失或未定义。

我的代码:

const data = [{Key: 56}, {Key: undefined}, {}, {Key: 44}]

const keys = data.reduce((prev, curr) => {
  if (curr.Key) {
    return [...prev, curr.Key];
  } else return prev;
}, []);
Run Code Online (Sandbox Code Playgroud)

它作为普通 JS 工作得很好,但 TS 编译器不喜欢它。游乐场链接

如何解决这个问题?主要是我做错了什么?我是TS菜鸟。

错误:

No overload matches this call.  

Overload 1 of 3, '(callbackfn: (previousValue: { Key: number; } | { Key: undefined; } | { Key?: undefined; }, currentValue: { Key: number; } | { Key: undefined; } | { Key?: undefined; }, currentIndex: number, array: ({ Key: number; } | { ...; } | { ...; })[]) => { ...; } | ... 1 more ... | { ...; }, initialValue: { ...; } | ... 1 more ... | { ...; }): { ...; } | ... 1 more ... | { ...; }', gave the following error.  
Argument of type '(prev: never[], curr: { Key: number; } | { Key: undefined; } | { Key?: undefined; }) => number[]' is not assignable to parameter of type '(previousValue: { Key: number; } | { Key: undefined; } | { Key?: undefined; }, currentValue: { Key: number; } | { Key: undefined; } | { Key?: undefined; }, currentIndex: number, array: ({ Key: number; } | { ...; } | { ...; })[]) => { ...; } | ... 1 more ... | { ...; }'.  
Types of parameters 'prev' and 'previousValue' are incompatible.  
Type '{ Key: number; } | { Key: undefined; } | { Key?: undefined; }' is not assignable to type 'never[]'.  
Type '{ Key: number; }' is missing the following properties from type 'never[]': length, pop, push, concat, and 26 more.  
Overload 2 of 3, '(callbackfn: (previousValue: never[], currentValue: { Key: number; } | { Key: undefined; } | { Key?: undefined; }, currentIndex: number, array: ({ Key: number; } | { Key: undefined; } | { Key?: undefined; })[]) => never[], initialValue: never[]): never[]', gave the following error.  
Argument of type '(prev: never[], curr: { Key: number; } | { Key: undefined; } | { Key?: undefined; }) => number[]' is not assignable to parameter of type '(previousValue: never[], currentValue: { Key: number; } | { Key: undefined; } | { Key?: undefined; }, currentIndex: number, array: ({ Key: number; } | { Key: undefined; } | { Key?: undefined; })[]) => never[]'.  
Type 'number[]' is not assignable to type 'never[]'.  
Type 'number' is not assignable to type 'never'.
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 15

将累加器 ( ) 的类型指定[]number[]( TS Playground ):

const keys = data.reduce((prev, curr) => {
  if (curr.Key) {
    return [...prev, curr.Key];
  } else return prev;
}, [] as number[]);
Run Code Online (Sandbox Code Playgroud)