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?
To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
Enum. GetName(Type, Object) Method is used to get the name of the constant in the specified enumeration that has the specified value. Syntax: public static string GetName (Type enumType, object value);
The java.lang.Enum.name() method returns the name of this enum constant, exactly as declared in its enum declaration.
valueOf() method returns the enum constant of the specified enumtype with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.
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
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