Typescript中的函数重载具有意外行为 .
看一下函数重载example,返回值签名是函数重载的一部分 . 但是,返回类型似乎完全被忽略了 . Typescript没有必要'pick'正确的函数参数签名,最困扰我的是,它不用于检查正确的返回值 .
如果卡的返回值从数字更改为字符串,则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'
}
}
我的问题是:我是否正确解释了过载机制,所以提供一个不必要的返回值签名或者这是一个错误?
1 回答
当我调用你的函数时,我得到以下类型的返回:
这使我不必手动指定它:
如果你要“错误地”使用它们,你确实会得到关于类型的错误:
因此,确实根据您传递的参数选择了重载 - 并根据所选的重载调整返回类型 .
View this example on the TypeScript Playground .