【问题标题】:Function overloading error: TS7006:Parameter 'x' implicitly has an 'any' type函数重载错误:TS7006:参数“x”隐式具有“任何”类型
【发布时间】:2017-06-27 19:58:24
【问题描述】:

这里是一个函数重载的例子,发布在官方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 };
    }
}

当我将此代码放入我的工作打字稿文件时,我收到错误:

错误:(5, 19) TS7006:Parameter 'x' 隐含一个 'any' 类型。

如何使这个例子工作?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    那是因为您可能打开了 noImplicitAny 标志。
    在这种情况下,您可以这样做:

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

    或者:

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

    【讨论】:

      猜你喜欢
      • 2020-02-02
      • 2020-01-06
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2021-11-17
      • 2017-08-21
      • 2021-07-20
      • 1970-01-01
      相关资源
      最近更新 更多