在Typescript中重载函数具有意想不到的行为。是函数重载中的返回类型签名没用吗?
看看函数重载example,返回值签名是函数重载的一部分。但是,返回类型似乎完全被忽略。 Typescript没有必要“挑选”正确的函数参数签名,而最让我困扰的是,它不用于检查正确的返回值。
如果卡的返回值从数字更改为字符串,Typescript不会给出任何警告。
function pickCard(x: {suit: string; card: number; }[]): number;
function pickCard(x: number): {suit: string; card: number; };
function pickCard(x): any {
// Check to see if we're working with an object/array
// if so, they gave us the deck and we'll pick the card
if (typeof x == "object") {
var pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
// Otherwise just let them pick the card
else if (typeof x == "number") {
var pickedSuit = Math.floor(x/13);
return { suit: suits[pickedSuit], card: x % 13 }; // <-- change to card: '13'
}
}
我的问题是:我会正确地解释过载机构,所以提供的是一个返回值的签名不是必需的,或者这一个错误?
至少在呼叫方检查过吗? (如果你打电话给第一个超载,当你把结果看作是数字以外的东西时它会发出cro)声) – Thilo 2014-09-10 10:14:51
当pickcard被调用'15'(字符串)而不是15(数字)时,它会发出抱怨。如果'返回pickCard'改为'return'someString''它不会抱怨。 – donnut 2014-09-10 10:26:04
不,我的意思是,根据选择正确的过载,来电方是否得到适当的返回值类型推断?根据@史蒂芬芬顿的回答,它的确如此。所以你在这里有一些价值,即使它没有完全检查函数的实现,它也检查调用代码。 – Thilo 2014-09-10 11:01:31