gpt4 book ai didi

arrays - TypeScript:reduce 函数 - 没有重载匹配这个调用

转载 作者:行者123 更新时间:2023-12-04 01:07:56 26 4
gpt4 key购买 nike

尝试编写一个基本的 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 编译器不喜欢它。 Playground Link
如何解决这个问题?主要是我做错了什么?我是 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'.

最佳答案

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

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

关于arrays - TypeScript:reduce 函数 - 没有重载匹配这个调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65711371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com