Jochen Kühner Jochen Kühner - 4 months ago 10
TypeScript Question

get enum values from a Stringvariable with enum name

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?

Answer

You can get enum instance from window["EnumName"]:

enum MyEnum {
    First, Second
}

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?