EN
TypeScript - convert enum to string
12
points
In TypeScript it is possible to get enum name in following way.
1. Getting enum
name by value from compiled in data example
enum Fruit {
Apple, // 0
Orange, // 1
Cherry // 2
}
enum Pet {
Dog = 'Dog',
Cat = 'Cat',
Rabbit = 'Rabbit'
}
console.log(Fruit[Fruit.Apple]);
console.log(Fruit[Fruit.Orange]);
console.log(Fruit[Fruit.Cherry]);
console.log(Pet[Pet.Dog]);
console.log(Pet[Pet.Cat]);
console.log(Pet[Pet.Rabbit]);
Output:
Apple
Orange
Cherry
Dog
Cat
Rabbit
2. Getting enum
name by value with custom logic example
class EnumReflection<T> {
private names : any = { };
public constructor(object : T) {
for(let name in object) {
let value = object[name];
this.names[value] = name;
}
}
public getName(value : string | number) : string {
return this.names[value] || null;
}
}
Example:
enum Fruit {
Apple,
Orange,
Cherry
}
let reflection = new EnumReflection(Fruit);
console.log(reflection.getName(Fruit.Apple));
console.log(reflection.getName(Fruit.Orange));
console.log(reflection.getName(Fruit.Cherry));
Output:
Apple
Orange
Cherry