Languages
[Edit]
EN

TypeScript - convert enum to string

9 points
Created by:
Selina-Miranda
567

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join