Languages
[Edit]
EN

TypeScript - convert enum to string

9 points
Created by:
Kate_C
2854

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

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍