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
}
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With