Get an array of string literal type values

I need to get a complete list of all the possible values ​​for a string literal.

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

Is there any way to achieve this?

+5
source share
2 answers

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

+1
source

The listing can 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 does not create a character that can be used at run time, it only creates an alias in the type system. Therefore, you cannot use it as an argument to a function.

If you need to have string values ​​for the YesNo type, you can use the trick (since the string values ​​of the enumerations are not 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 the possible values ​​for YesNoEnum , that is, ['Yes', 'No']. It's a little ugly, but it will work.

Honestly, I would only go with such a static variable:

 type YesNo = 'yes' | 'no'; const YES_NO_VALUES: YesNo[] = ['yes', 'no']; 
+5
source

Source: https://habr.com/ru/post/1268166/


All Articles