首页 > 解决方案 > Lodash _.reduce()“预期 2-3 个参数,但在 TypeScript 中得到 2”错误

问题描述

我正在尝试减少ListAdItemResponse[]收集以{[name: string]: Date}输入我的一个测试并检查每个后续发布的日期是否在当前日期之前(例如按publishedAt降序排序):

 _.reduce<ListAdItemResponse, {[name: string]: Date}>(
   data,
   (result, val) => {
     expect(new Date(val.publishedAt)).to.be.beforeTime(
       new Date(result.publishedAt),
      )
     return {publishedAt: val.publishedAt}
   })

使用 TypeScript 2.9.2,我得到了这个奇怪的矛盾错误(“预期 2-3 个参数,但得到 2 个”)。根据 Lodash 文档,第三个参数是可选的,但无论我尝试什么,我都无法克服这个错误。知道这里可能有什么问题吗?谢谢。

PS这编译没有错误,但显然打破了我的测试:

_.reduce<ListAdItemResponse, {[name: string]: Date}>(
  data,
  (result, val) => {
    expect(new Date(val.publishedAt)).to.be.beforeTime(
      new Date(result.publishedAt),
    )
    return {publishedAt: val.publishedAt}
  }, {}) // with {} added as 3rd argument

2018 年 9 月 2 日更新:

根据@Matt 的建议,我尝试过这种方法,但这次出现了 3 个编译错误。看起来它期望alis.data集合类型{[name: string]: Date}而不是ListAdItemResponse[]现在:

_.reduce<{[name: string]: Date}>(
  alis.data, // <-- error 1: Argument of type 'ListAdItemResponse[]' is not assignable to parameter of type '{ [name: string]: Date; } | null | undefined'.Type 'ListAdItemResponse[]' is not assignable to type '{ [name: string]: Date; }'. Index signature is missing in type 'ListAdItemResponse[]'.
  (result, val) => { // <-- errors 2,3: Parameter 'result' implicitly has an 'any' type. Parameter 'val' implicitly has an 'any' type.
    expect(new Date(val.publishedAt)).to.be.beforeTime(
      new Date(result.publishedAt),
    )
    return {publishedAt: val.publishedAt}
  })

标签: typescriptlodash

解决方案


如果你想省略第三个参数,那么输入项的类型和累加器应该是相同的,所以你应该只传递一个类型参数:

_.reduce<{[name: string]: Date}>(...)

我针对矛盾的错误消息提交了一个问题。

第二轮

尽管错误的数量增加了,但您离目标更近了!假设ListAdItemResponse看起来像这样的定义:

interface ListAdItemResponse {
    publishedAt: Date;
    // other fields...
}

那么您的调用与_.reduce您想要的重载不匹配,因为它没有索引签名,因此ListAdItemResponse不可分配。{[name: string]: Date}(令人困惑的是,TypeScript 的错误 #1 是基于错误的假设,即您想要一个不同的重载来减少对象的键。)对象字面量类型有一个特殊的例外,比如您从 reducer 返回的那个。您可能应该做的是将状态类型更改为,{publishedAt: Date}因为这是您使用的唯一字段:

_.reduce<{publishedAt: Date}>(...)

这应该也会使错误 #2 和 #3 消失。


推荐阅读