6

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?

1
  • you could use reflection, something like this post stackoverflow.com/questions/15338610/…. Anyway I would first think if that is the right way to go or you can access it in a "normal" way Commented Aug 2, 2016 at 11:50

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Window[enumname] did not work, maybe because we use namespaces. But "eval(enumname)" did work.
Is there a React friendly alternative to this?
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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.