Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum reverse lookup [duplicate]

Tags:

typescript

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
like image 867
Chin Avatar asked Feb 13 '23 21:02

Chin


1 Answers

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
like image 64
basarat Avatar answered Feb 19 '23 15:02

basarat