Typscript的新手。
尝试使用Lodash进行简单的归约,
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[]'.
有人可以让我知道此错误的原因以及如何解决该错误吗?
答案 0 :(得分:2)
您的减速器有问题:
(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
的值等于数组中 not 的数字。
您需要添加一个值并仍然返回一个数组:
prev.push(scene);
return prev;
但是,由于在条件运算符中这很麻烦,因此,如果使用,则可以使加法成为单个表达式:
Array#concat
(prev, scene) =>
scene.collectionId === action.collectionId
? prev.concat(scene)
^^^^^^^^^^^^^^^^^^
: prev
(prev, scene) =>
scene.collectionId === action.collectionId
? [...prev, scene]
^^^^^^^^^^^^^^^^
: prev