这是在官方网站上发布的函数重载的示例:
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 };
}
}
Run Code Online (Sandbox Code Playgroud)
当我将此代码放入工作的打字稿文件时,出现错误:
错误:(5,19)TS7006:参数'x'隐式具有'any'类型。
如何使这个例子起作用?
那是因为您可能已经noImplicitAny标记了。
在这种情况下,您可以执行以下操作:
function pickCard(x: any): any {
...
}
Run Code Online (Sandbox Code Playgroud)
要么:
function pickCard(x: number | {suit: string; card: number; }[]): any {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
386 次 |
| 最近记录: |