[英]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.