Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of string literal type values

Tags:

typescript

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?

like image 367
Kali Avatar asked May 24 '17 09:05

Kali


2 Answers

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'];
like image 199
Kirill Dmitrenko Avatar answered Nov 20 '22 11:11

Kirill Dmitrenko


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).

like image 8
Kali Avatar answered Nov 20 '22 12:11

Kali