Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Enum Name as String in TypeScript

I'm trying to find a way to convert the name of an enum to a string. If I have the Response enum below, how can I convert or extract 'Response' to a string? One of my functions takes any enum as input and I need the name, not the type of enum to execute other code.

enum Response 
{
    No = 0,
    Yes = 1 
}
like image 314
jurgen w Avatar asked Mar 05 '23 04:03

jurgen w


1 Answers

No, you can't convert an enum name to a string as type information is stored only during compilation. You have to pass additional parameters, specifying what enum are you using.


But you can use square brackets to convert enum value to a string and back:

Fiddle

enum YesNo {
    No = 0,
    Yes = 1, 
}

console.log(YesNo[YesNo.Yes]);
console.log(YesNo[YesNo.No]);
console.log(YesNo["Yes"]);
console.log(YesNo["No"]);
console.log(YesNo[1]);
console.log(YesNo[0]);

This code compiles into:

var YesNo;
(function (YesNo) {
YesNo[YesNo["No"] = 0] = "No";
YesNo[YesNo["Yes"] = 1] = "Yes";
})(YesNo || (YesNo = {}));
console.log(YesNo[YesNo.Yes]);
console.log(YesNo[YesNo.No]);
console.log(YesNo["Yes"]);
console.log(YesNo["No"]);
console.log(YesNo[1]);
console.log(YesNo[0]);
like image 86
Qwertiy Avatar answered Mar 07 '23 00:03

Qwertiy