【问题标题】:Once again: typescript function overload再次:打字稿函数重载
【发布时间】:2019-07-04 11:17:56
【问题描述】:

通常我可以掌握打字稿语言的大部分功能,但有时函数重载仍然相当具有挑战性。

我无法理解为什么 typescript 编译器不断在以下代码 (mcve) 上抛出 error TS2394: Overload signature is not compatible with function implementation:

class Editor {
  replace(
    searchValue: { [Symbol.match](string: string): RegExpMatchArray; }, 
    replaceValue: string,
  ): this;

  replace(
    searchValue: { [Symbol.match](string: string): RegExpMatchArray; },
    replacer: (substring: string, ...args: any[]) => string,
  ): this {
    return this;
  }
}

唯一的区别在于第二个参数:string 或 (substring: string, ...args: any[]) => string。

为什么编译器不能将它们组合成string | (substring: string, ...args: any[]) => string?

【问题讨论】:

    标签: typescript typescript-types


    【解决方案1】:

    最后一个签名是实现签名,必须与 all 重载兼容。在这种情况下,Editor 只定义了一个公共签名,即带有string 的签名,而实现签名是带有回调的签名。这可能不是您的意图,您可能希望两个签名都可用:

    class Editor {
        replace(
            searchValue: { [Symbol.match](string: string): RegExpMatchArray; }, 
            replaceValue: string,
        ): this;
        replace(
            searchValue: { [Symbol.match](string: string): RegExpMatchArray; },
            replacer: (substring: string, ...args: any[]) => string,
        ): this
        replace(
            searchValue: { [Symbol.match](string: string): RegExpMatchArray; },
            replacer: string | ((substring: string, ...args: any[]) => string),
        ): this {
        return this;
        }
    }
    

    至于为什么编译器不能将实现签名拼接在一起,重载与实现签名的差异可能会变得相当大(实现签名有时只使用any),可能认为最好允许开发人员选择具有最小兼容性检查的实现签名,以防止意外错误。

    【讨论】:

      猜你喜欢
      • 2020-05-20
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 2019-01-24
      • 2022-06-11
      • 1970-01-01
      相关资源
      最近更新 更多