【问题标题】:How to do a named export of an overloaded function in Typescript?如何在 Typescript 中对重载函数进行命名导出?
【发布时间】:2020-09-18 09:45:29
【问题描述】:

pickCard.ts

这个例子来自:

https://www.typescriptlang.org/docs/handbook/functions.html#overloads

function pickCard(x: { suit: string; card: number }[]): number;
function pickCard(x: number): { suit: string; card: number };
function pickCard(x: any): 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 };
  }
}

export pickCard; // DOES NOT WORK

我不能使用像 export const pickCard = () => {}; 这样的函数表达式,因为重载不适用于函数表达式。

问题

如何对pickCard 函数进行命名导出。注意:名字应该是pickCard

【问题讨论】:

    标签: javascript typescript export overloading


    【解决方案1】:

    这对我有用:

    export function pickCard(x: { suit: string; card: number }[]): number;
    export function pickCard(x: number): { suit: string; card: number };
    export function pickCard(x: any): 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 };
      }
    }
    

    在其他文件中使用:

    import { pickCard } from ".";
    
    pickCard([{ suit: 'test', card: 10 }]);
    pickCard(21);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      相关资源
      最近更新 更多