【发布时间】:2020-06-01 20:33:07
【问题描述】:
考虑以下函数重载和带有错误的实现。
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。 但是打字稿不这样做 - 它只做 3.
是否可以在打字稿中实现上述行为?
【问题讨论】:
-
查看此线程的讨论:github.com/microsoft/TypeScript/issues/13225。 TL;DR:TypeScript 中的函数重载只是一种覆盖检查,实际上并不尝试验证返回类型。