考虑下面的函数重载和实现有bug。
function foo(param: number): boolean;
function foo(param: string): string;
function foo(param) {
if (typeof param === "number") {
// typescript does not complain that 12 is not boolean
return 12;
} else if (typeof param === "string") {
// typescript does not complain that {} is not string
return {};
}
}
下面是如何解释它。
如果函数 foo
接受数字参数,应该返回布尔值。
如果功能 foo
接受字符串参数,应该返回字符串
屡禁不止
当然,类型检查器可以通过分析函数代码来验证1&2,但typescript不这样做--它只做3。
有没有可能在typescript中实现上述行为?
移除 function foo(param)
. 这就增加了第三个重载,即 param
打成 any
.
function foo(param: number): boolean;
function foo(param: string): string {
if (typeof param === "number") {
return 12;
} else if (typeof param === "string") {
return {};
}
}