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?
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'];
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With