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

标签 typescript lodash

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/

相关文章:

javascript - 如何正确链接 lodash 函数调用

javascript - 将单个值转换为数组

javascript - Lodash过滤器和功能组合

TypeScript - 如何键入自实例化函数

javascript - 如何在 typescript 中获取 Date.timeIntervalSinceReferenceDate?

TypeScript 编译器错误 : Cannot initialize ActiveScript

javascript - 当行为 :smooth 时,去抖不适用于 js scrollIntoView

typescript - 关于 rxjs debounceTime 的困惑

javascript - Typescript 到 Javascript 导出

generics - 带有泛型的 typescript 问题 : Cannot read property 'prototype' of undefined