陣列 - TypeScript:reduce 函數 - 沒有符合此呼叫的重載
嘗試編寫一個基本的 reducer,從一個物件陣列中返回一個鍵的值的陣列。這些鍵有些可能缺失或未定義。
我的程式碼:
const data = [{Key: 56}, {Key: undefined}, {}, {Key: 44}]
const keys = data.reduce((prev, curr) => {
if (curr.Key) {
return [...prev, curr.Key];
} else return prev;
}, []);
作為純 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'.
答案#1
將累加器 ([]) 的類型指定為 number[](TS playground):
const keys = data.reduce((prev, curr) => {
if (curr.Key) {
return [...prev, curr.Key];
} else return prev;
}, [] as number[]);
答案#2
你需要指定 reduce 函數第二個參數的類型。
試試這個
const data = [{key: 56}, {key: undefined}, {}, {key: 44}]
const keys = data.reduce((keys, current) => {
if (current.key) {
return [...keys, current.key];
} else return keys;
}, [] as number[]);
編輯:我之前急著回答,另外為了改善程式碼的可讀性,我建議你做一些修改,比如將屬性命名為 key 而不是 Key,以及為 reduce 函數的參數取一些更好的名字
