以下是官方website上发布的函数重载示例:
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 };
}
}
当我将此代码放入我的工作typscript文件时,我收到错误:
错误:(5,19)TS7006:参数' x'隐含地有一个“任何”的类型。
如何让这个例子起作用?
答案 0 :(得分:4)
那是因为你可能有noImplicitAny
标志。
在这种情况下,你可以这样做:
function pickCard(x: any): any {
...
}
或者:
function pickCard(x: number | {suit: string; card: number; }[]): any {
...
}