In Typescript I get a string
variable that contains the name of my defined enum
.
How can I now get all values of this enum?
In Typescript I get a string
variable that contains the name of my defined enum
.
How can I now get all values of this enum?
Typescript enum:
enum MyEnum {
First, Second
}
is transpiled to JavaScript object:
var MyEnum;
(function (MyEnum) {
MyEnum[MyEnum["First"] = 0] = "First";
MyEnum[MyEnum["Second"] = 1] = "Second";
})(MyEnum || (MyEnum = {}));
You can get enum
instance from window["EnumName"]
:
const MyEnumInstance = window["MyEnum"];
Next you can get enum member values with:
const enumMemberValues: number[] = Object.keys(MyEnumInstance)
.map((k: any) => MyEnumInstance[k])
.filter((v: any) => typeof v === 'number').map(Number);
And enum member names with:
const enumMemberNames: string[] = Object.keys(MyEnumInstance)
.map((k: any) => MyEnumInstance[k])
.filter((v: any) => typeof v === 'string');
See also How to programmatically enumerate an enum type in Typescript 0.9.5?
As an alternative to the window
approach that the other answers offer, you could do the following:
enum SomeEnum { A, B }
let enumValues:Array<string>= [];
for(let value in SomeEnum) {
if(typeof SomeEnum[value] === 'number') {
enumValues.push(value);
}
}
enumValues.forEach(v=> console.log(v))
//A
//B