Get Enum Element Name in Typescript

/ February 17, 2018/ Typescript

(Last Updated On: February 18, 2018) Sometimes while debugging a Typescript base project we need to check if a parameter has the correct Enum type. Usually we have something like

let myVariable = myEnum.myType
console.log(`myVariale is ${myVariable}`);

but that will print just a number (the index position of the Enum). If we need to print the Enum value name we can see in the transpiled version of an Enum to get some help.

Ad:


Typescript Source

enum myEnum{
    Up,
    Down,
    Left,
    Right,
    myType
}
console.log(myEnum.myType); // outputs 4

Transpiled Javascript

var myEnum;

(function (myEnum) {
    myEnum[myEnum["Up"] = 0] = "Up";
    myEnum[myEnum["Down"] = 1] = "Down";
    myEnum[myEnum["Left"] = 2] = "Left";
    myEnum[myEnum["Right"] = 3] = "Right";
    myEnum[myEnum["myType"] = 4] = "myType";
})(myEnum || (myEnum = {}));

console.log(myEnum.myType);

Did you see it? myEnum is just an Object with numerical and string keys. If we simplify it more we have:

Transpiled and Simplified Javascript

var myEnum;
(function (myEnum) {
  
    myEnum["Up"] = 0;
    myEnum[0] = "Up";
    
    myEnum["Down"] = 1;
    myEnum[1] = "Down";
    
    myEnum["Left"] = 2;
    myEnum[2] = "Left";
    
    myEnum["Right"] = 3;
    myEnum[3] = "Right";
    
    myEnum["myType"] = 4;
    myEnum[4] = "myType";
    
})(myEnum || (myEnum = {}));
console.log(myEnum.myType) // Outputs 4;

Now is really clear, each Enum.someValue has its numerical pair and we can use this numerical pair to get the name in this way:

enum myEnum{
    Up,
    Down,
    Left,
    Right,
    myType
}
console.log(myEnum.myType); // outputs 4
console.log(myEnum[myEnum.myType]); //outputs myType
Ad:


Spread the love
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments