Suppose I have an enum:
enum Color {Red = 1, Green, Blue};
If I have a number, I can get the enum key by doing this:
var colorName: string = Color[2]; // colorName = "Green"
However, that gives me a string. How can I make it so that I get a variable of type Color instead? i.e.:
colorName : Color == Color.Green
Don't index it by number (which will give you a string) and just use the named member.Typescript would happily let you assign a number to an enum i.e.
enum Color {Red = 1, Green, Blue};
var foo:Color = Color.Green; // effectively foo = 2;
console.log(foo == Color.Green); // true
Alternatively if you already have the string you can index Color by a string to get its number i.e:
enum Color {Red = 1, Green, Blue};
var colorName:string = Color[2];
var color: Color = Color[colorName];
console.log(color == Color.Green); // true
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