重載
函數(shù)重載示例:
let suits = ["hearts", "spades", "clubs", "diamonds"];
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") {
let pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
// Otherwise just let them pick the card
else if (typeof x == "number") {
let pickedSuit = Math.floor(x / 13);
return { suit: suits[pickedSuit], card: x % 13 };
}
}
編譯器會(huì)查找重載列表,嘗試使用第一個(gè)匹配的定義。 因此,在定義重載的時(shí)候,一定要把最精確的定義放在最前面。
注意,function pickCard(x): any 并不是重載列表的一部分,因此這里只有兩個(gè)重載:一個(gè)是接收對(duì)象,另一個(gè)接收數(shù)字。以其它參數(shù)調(diào)用 pickCard 會(huì)產(chǎn)生錯(cuò)誤。