Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get enum values by enum name string

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?

like image 994
Jochen Kühner Avatar asked Aug 02 '16 11:08

Jochen Kühner


People also ask

How do you find the value of an 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.

How do I find the enum name?

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

What does enum name return?

The java.lang.Enum.name() method returns the name of this enum constant, exactly as declared in its enum declaration.

What is enum valueOf?

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.


2 Answers

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?

like image 93
mixel Avatar answered Oct 06 '22 05:10

mixel


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
like image 38
dimitrisli Avatar answered Oct 06 '22 05:10

dimitrisli