7

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?

mixel
  • 25,177
  • 13
  • 126
  • 165
Jochen Kühner
  • 1,385
  • 2
  • 18
  • 43
  • you could use reflection, something like this post http://stackoverflow.com/questions/15338610/dynamically-loading-a-typescript-class-reflection-for-typescript. Anyway I would first think if that is the right way to go or you can access it in a "normal" way – iberbeu Aug 02 '16 at 11:50

2 Answers2

6

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?

Community
  • 1
  • 1
mixel
  • 25,177
  • 13
  • 126
  • 165
2

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
dimitrisli
  • 20,895
  • 12
  • 59
  • 63
  • If we had the instance of the enum then it is easy to get the list of values. The questions was how do we get the enum instance from the string value. – Dhanraj Acharya Sep 25 '20 at 05:53