2017-06-27 66 views
0

這裏是一個被官方website公佈的函數重載的例子:函數重載錯誤:TS7006:參數「X」隱含有一個「任意」類型

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文件我得到錯誤:

Error:(5, 19) TS7006:Parameter 'x' implicitly has an 'any' type.

如何使此示例工作?

回答

2

這是因爲你可能有noImplicitAny標誌。
在這種情況下,你可以這樣做:

function pickCard(x: any): any { 
    ... 
} 

或者:

function pickCard(x: number | {suit: string; card: number; }[]): any { 
    ... 
} 
相關問題