Get enum values ​​by enumeration name string

In Typescript, I get a variable stringthat contains the name of my defined one enum.

How can I get all the values ​​of this listing?

+4
source share
2 answers

Typescript enumeration:

enum MyEnum {
    First, Second
}

converts to a JavaScript object:

var MyEnum;
(function (MyEnum) {
    MyEnum[MyEnum["First"] = 0] = "First";
    MyEnum[MyEnum["Second"] = 1] = "Second";
})(MyEnum || (MyEnum = {}));

You can get an instance enumfrom window["EnumName"]:

const MyEnumInstance = window["MyEnum"];

Next, you can get the values ​​of an enumeration member with:

const enumMemberValues: number[] = Object.keys(MyEnumInstance)
        .map((k: any) => MyEnumInstance[k])
        .filter((v: any) => typeof v === 'number').map(Number);

And list the 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 enumeration type in Typescript 0.9.5?

+5
source

window, , :

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
+2

Source: https://habr.com/ru/post/1649899/


All Articles