51

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?

2 Answers 2

24

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'];
Sign up to request clarification or add additional context in comments.

2 Comments

When I try @KirillDmitrenko's suggestion. My array allows non literal values as well. For example const YES_NO_VALUES: YesNo[] = [ 'yes', 'no', 'maybe'];
Shouldn't the getEnumValues function be: function getEnumValues(e: EnumObject): string[] { return Object.keys(e).map((_, idx: number): string => e[idx]); }
9

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

1 Comment

There is no bidirectional mapping for string enums however

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.