Getting enum keys in TypeScript

They can be your friend..

They can be your friend..

While working on a task, my colleague stumbled upon a quirky problem.

He tried to fetch all keys out of an enum but ended up with both the keys and values. We tried figuring out why this happens and once we saw the compiled javascript everything was clear.

Let’s have a look:

enum SomeEnum { 
    A,
    B,
    C,
    D
}

The enum above will be transpiled into:

var SomeEnum;
(function (SomeEnum) {
    SomeEnum[SomeEnum["A"] = 0] = "A";
    SomeEnum[SomeEnum["B"] = 1] = "B";
    SomeEnum[SomeEnum["C"] = 2] = "C";
    SomeEnum[SomeEnum["D"] = 3] = "D";
})(SomeEnum || (SomeEnum = {}));

The thing here that is important is to realize that with this output the final object will have A, B, C, and D as keys as well as 0, 1, 2, and 3.

Because of the SomeEnum[“A”] = 0 assignment we will create a property “A” with the value of 0 and then (as part of the larger SomeEnum[SomeEnum["A"] = 0] = "A"; assignment) create a property “0” with the value of "A” .

If you try to get the keys (with Object.keys()) you will get the mentioned A, B, C, D, 0, 1, 2, and 3.

To get only they keys or member names you can do something like this:

let enums = Object.keys(SomeEnum).filter(x => !(parseInt(x) >= 0));
console.log("Enums", enums); //Enums: A, B, C, D

Hope this will help you out in your TypeScript quest.

Until next time.

Happy Coding!