繁体   English   中英

再次:打字稿函数重载

[英]Once again: typescript function overload

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

我无法error TS2394: Overload signature is not compatible with function implementation为什么error TS2394: Overload signature is not compatible with function implementation编译器不断抛出error TS2394: Overload signature is not compatible with function implementation on the following code (mcve):

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修补在一起? string | (substring: string, ...args: any[]) => string ?

最后一个签名是实现签名,必须与所有重载兼容。 在这种情况下, 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 ),可能认为最好让开发人员选择实现签名与最小的兼容性检查,以防止意外错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM