Languages
[Edit]
EN

TypeScript - convert enum to string

9 points
Created by:
Kate_C
19810

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

3. References

  1.  Reverse mappings - Microsoft Docs
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join