Non-number values for enum in Typescript

Use non-numbers in Typescript enums.

enums have the following typical definition and usage -

enum Colors {
  red,
  blue,
  green
}

console.log(Colors[1]);
// blue

Or, the numbers can be explicitly specified..

enum Colors {
  red = 1,
  blue = 2,
  green = 3
}

console.log(Colors[1]);
// red

console.log(Colors["red"]);
// 1

Since Typescript v2.2, we can also specify non-numbers against the value.

enum FruitColors {
    apple = "red",
    orange = "orange",

}

console.log(FruitColors['apple']);
// red

Or, you could go crazy with more complex objects (but, why?).

enum Fruit {
  apple = <any>{ color: "red", flavor: "sweet" },
  orange = <any>{ color: "orange", flavor: "sweet" }
}

console.log(Fruit["apple"]);
// { color: 'red', flavor: 'sweet' }
comments powered by Disqus