gpt4 book ai didi

typescript - Lodash Reduce with Typescript - 没有重载匹配此调用

转载 作者:行者123 更新时间:2023-12-04 10:46:43 25 4
gpt4 key购买 nike

Typscript 新手..

尝试使用 Lodash 进行简单的 reduce,

let collectionScenes: IScene[] = reduce(
scenes,
(prev, scene) =>
scene.collectionId === action.collectionId
? prev.push(scene)
: prev,
[],
)

发生这种崩溃:

(19,41): No overload matches this call.
Overload 1 of 6, '(collection: IScene[], callback: MemoListIterator<IScene, any[], IScene[]>, accumulator: any[]): any[]', gave the following error.
Argument of type 'IKeyArray<IScene>' is not assignable to parameter of type 'IScene[]'.
Type 'IKeyArray<IScene>' is missing the following properties from type 'IScene[]': length, pop, push, concat, and 26 more.
Overload 2 of 6, '(collection: List<IScene>, callback: MemoListIterator<IScene, any[], List<IScene>>, accumulator: any[]): any[]', gave the following error.
Argument of type 'IKeyArray<IScene>' is not assignable to parameter of type 'List<IScene>'.
Property 'length' is missing in type 'IKeyArray<IScene>' but required in type 'List<IScene>'.
Overload 3 of 6, '(collection: IKeyArray<IScene>, callback: MemoObjectIterator<IScene, any[], IKeyArray<IScene>>, accumulator: any[]): any[]', gave the following error.
Type 'number | any[]' is not assignable to type 'any[]'.
Type 'number' is not assignable to type 'any[]'.

谁能告诉我这个错误是什么以及如何解决?

最佳答案

你的 reducer 有问题:

(prev, scene) =>
scene.collectionId === action.collectionId
? prev.push(scene)
^^^^^^^^^^^^^^^^
: prev

Array#push返回一个数字。这是数组的新长度:

const arr = ["a", "b", "c"];

console.log(arr.length);
console.log(arr.push("d"));
console.log(arr.push("e"));

因此,在 reduce 的下一次迭代中,累加器 prev 的值将等于数组中的那个数字而不是

您需要添加一个值并仍然返回一个数组:

prev.push(scene);
return prev;

但是因为这在条件运算符中很麻烦,所以如果您使用:

Array#concat

(prev, scene) =>
scene.collectionId === action.collectionId
? prev.concat(scene)
^^^^^^^^^^^^^^^^^^
: prev

Spread syntax

(prev, scene) =>
scene.collectionId === action.collectionId
? [...prev, scene]
^^^^^^^^^^^^^^^^
: prev

关于typescript - Lodash Reduce with Typescript - 没有重载匹配此调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59672114/

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