Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

TypeScript - convert enum to string

0 contributions
9 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

3. References

  1.  Reverse mappings - Microsoft Docs
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey đź‘‹
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more