5

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
Chin
  • 19,717
  • 37
  • 107
  • 164

1 Answers1

11

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
basarat
  • 261,912
  • 58
  • 460
  • 511