EN
TypeScript - convert enum to string
12 points
In TypeScript it is possible to get enum name in following way.
xxxxxxxxxx
1
enum Fruit {
2
Apple, // 0
3
Orange, // 1
4
Cherry // 2
5
}
6
7
enum Pet {
8
Dog = 'Dog',
9
Cat = 'Cat',
10
Rabbit = 'Rabbit'
11
}
12
13
console.log(Fruit[Fruit.Apple]);
14
console.log(Fruit[Fruit.Orange]);
15
console.log(Fruit[Fruit.Cherry]);
16
17
console.log(Pet[Pet.Dog]);
18
console.log(Pet[Pet.Cat]);
19
console.log(Pet[Pet.Rabbit]);
Output:
xxxxxxxxxx
1
Apple
2
Orange
3
Cherry
4
Dog
5
Cat
6
Rabbit
xxxxxxxxxx
1
class EnumReflection<T> {
2
private names : any = { };
3
4
public constructor(object : T) {
5
for(let name in object) {
6
let value = object[name];
7
8
this.names[value] = name;
9
}
10
}
11
12
public getName(value : string | number) : string {
13
return this.names[value] || null;
14
}
15
}
Example:
xxxxxxxxxx
1
enum Fruit {
2
Apple,
3
Orange,
4
Cherry
5
}
6
7
let reflection = new EnumReflection(Fruit);
8
9
console.log(reflection.getName(Fruit.Apple));
10
console.log(reflection.getName(Fruit.Orange));
11
console.log(reflection.getName(Fruit.Cherry));
12
Output:
xxxxxxxxxx
1
Apple
2
Orange
3
Cherry