39

I need to get a full list of all possible values for a string literal.

type YesNo = "Yes" | "No";
let arrayOfYesNo : Array<string> = someMagicFunction(YesNo); //["Yes", "No"]

Is there any way of achiving this?

Kali
  • 811
  • 1
  • 8
  • 17

2 Answers2

19

Enumeration may help you here:

enum YesNo {
    YES,
    NO
}

interface EnumObject {
    [enumValue: number]: string;
}

function getEnumValues(e: EnumObject): string[] {
    return Object.keys(e).map((i) => e[i]);
}

getEnumValues(YesNo); // ['YES', 'NO']

type declaration doesn't create any symbol that you could use in runtime, it only creates an alias in type system. So there's no way you can use it as a function argument.

If you need to have string values for YesNo type, you can use a trick (since string values of enums aren't part of TS yet):

const YesNoEnum = {
   Yes: 'Yes',
   No: 'No'
};

function thatAcceptsYesNoValue(vale: keyof typeof YesNoEnum): void {}

Then you can use getEnumValues(YesNoEnum) to get possible values for YesNoEnum, i.e. ['Yes', 'No']. It's a bit ugly, but that'd work.

To be honest, I would've gone with just a static variable like this:

type YesNo = 'yes' | 'no';
const YES_NO_VALUES: YesNo[] = ['yes', 'no'];
Kirill Dmitrenko
  • 3,474
  • 23
  • 31
  • 1
    When I try @KirillDmitrenko's suggestion. My array allows non literal values as well. For example `const YES_NO_VALUES: YesNo[] = [ 'yes', 'no', 'maybe'];` – jschank Jun 26 '17 at 15:55
  • Shouldn't the getEnumValues function be: ```function getEnumValues(e: EnumObject): string[] { return Object.keys(e).map((_, idx: number): string => e[idx]); }``` – Remi Sep 24 '20 at 12:31
8

Typescript 2.4 is finally released. With the support of string enums I no longer have to use string literals and because typescript enums are compiled to javascript I can access them at runtime (same approach as for number enums).

Kali
  • 811
  • 1
  • 8
  • 17