【问题标题】:Typescript doesn't select the correct overload打字稿没有选择正确的重载
【发布时间】:2017-04-30 13:31:04
【问题描述】:
  • 打字稿版本:2.1.4
  • @types/mongoose 版本:4.7.1

我使用猫鼬的类型:

post<T extends Document>(method: string, fn: (
  error: mongodb.MongoError, doc: T, next: (err?: NativeError) => void
) => void): this;

post<T extends Document>(method: string, fn: (
  doc: T, next: (err?: NativeError) => void
) => void): this;

在我的代码中:

function (schema: Schema) {
  schema.post('remove', function (doc, next) { });
}

它总是首先选择post定义,doc将是mongodb.MongoErrornext将是T

我错过了什么吗? 以及如何让它选择第二个post定义?

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    TypeScript 总是选择与指定参数匹配的 first 重载。因为被调用者可能会忽略函数参数,这意味着接受更高数量的回调的函数应该在更低数量的回调之后。

    第二个重载更具体(它可以处理比前一个重载更低总数量的函数),因此在这种情况下,第二个重载应该列在第一个重载之上。

    TL;DR:.d.ts 文件有一个错误,应该交换那两条 post 行。

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 2020-02-13
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2021-09-27
      • 1970-01-01
      • 2014-04-19
      相关资源
      最近更新 更多