Use non-numbers in Typescript enums.
enums have the following typical definition and usage -
1
2
3
4
5
6
7
8
9
|
enum Colors {
red,
blue,
green
}
console.log(Colors[1]);
// blue
|
Or, the numbers can be explicitly specified..
1
2
3
4
5
6
7
8
9
10
11
12
|
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.
1
2
3
4
5
6
7
8
|
enum FruitColors {
apple = "red",
orange = "orange",
}
console.log(FruitColors['apple']);
// red
|
Or, you could go crazy with more complex objects (but, why?).
1
2
3
4
5
6
7
|
enum Fruit {
apple = <any>{ color: "red", flavor: "sweet" },
orange = <any>{ color: "orange", flavor: "sweet" }
}
console.log(Fruit["apple"]);
// { color: 'red', flavor: 'sweet' }
|