cbdeveloper
cbdeveloper

Reputation: 31335

How to do a named export of an overloaded function in Typescript?

pickCard.ts

This is the example from:

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

I can't use a function expression like: export const pickCard = () => {}; because overloads won't work on function expressions.

QUESTION

How can I do a named export on the pickCard function. Note: the name should be pickCard

Upvotes: 0

Views: 1581

Answers (1)

AtaiLo
AtaiLo

Reputation: 111

This worked for me:

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 };
  }
}

Use in other file:

import { pickCard } from ".";

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

Upvotes: 2

Related Questions