为什么函数重载不提示错误?
Why does function overloading not prompt an error?
function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
return x + '1';
}
为什么这个函数重载可以打字稿?
我想限制数字输入数字输出和字符串输入字符串输出。
在我的函数实现中,我特意让数字输入字符串输出。我希望在编译这个 ts 文件时会抛出一条错误消息,但它没有。为什么?
环境:没有 tsconfig.json 且 tsc 版本为 4.4.3
打字稿并不完美。查看 Github issue #13235 了解有关此特定缺陷的更多信息。
基本上你的实现函数不知道重载签名的存在。它的类型是 return string | number
并且它是 returns string
,这是 return 的完全有效类型。就是这么简单。
是的,在这种情况下,即使代码编译没有错误,您也可能在运行时遇到类型错误。盲点,没有很好的办法覆盖。
为什么它不完美?好吧,从那个 Github 问题来看,这句话更能说明问题。
There doesn't seem to be much evidence that people are regularly making mistakes here in a way that we could reliably detect without introducing false positives. But the real problem is that any implementation here is going to be at least O(n^2) on the number of signatures, and there are many .d.ts files which have literally dozens of signatures per function. The cost and complexity of checking for "correctness" in overloads every time when the errors are so rare to begin with doesn't seem worth it.
FWIW,在您的情况下,您可能更愿意使用泛型。
您希望输出类型取决于输入类型:
function reverse<T extends string | number>(x: T): T {
// ...
}
function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
return x + '1';
}
为什么这个函数重载可以打字稿? 我想限制数字输入数字输出和字符串输入字符串输出。
在我的函数实现中,我特意让数字输入字符串输出。我希望在编译这个 ts 文件时会抛出一条错误消息,但它没有。为什么?
环境:没有 tsconfig.json 且 tsc 版本为 4.4.3
打字稿并不完美。查看 Github issue #13235 了解有关此特定缺陷的更多信息。
基本上你的实现函数不知道重载签名的存在。它的类型是 return string | number
并且它是 returns string
,这是 return 的完全有效类型。就是这么简单。
是的,在这种情况下,即使代码编译没有错误,您也可能在运行时遇到类型错误。盲点,没有很好的办法覆盖。
为什么它不完美?好吧,从那个 Github 问题来看,这句话更能说明问题。
There doesn't seem to be much evidence that people are regularly making mistakes here in a way that we could reliably detect without introducing false positives. But the real problem is that any implementation here is going to be at least O(n^2) on the number of signatures, and there are many .d.ts files which have literally dozens of signatures per function. The cost and complexity of checking for "correctness" in overloads every time when the errors are so rare to begin with doesn't seem worth it.
FWIW,在您的情况下,您可能更愿意使用泛型。
您希望输出类型取决于输入类型:
function reverse<T extends string | number>(x: T): T {
// ...
}