Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

TypeScript - convert enum to array

0 contributions
12 points

In TypeScript it is possible to get enum names or values in following way.

Custom enum reflection example

class EnumReflection {
    private static REGEXP : RegExp = /^[0-9]+$/g;

    private static isString<T>(name : string) : boolean {
        if(name.match(this.REGEXP))
            return false;

        return true;
    }

    public static getNames<T>(object : T) : Array<string> {
        let result = new Array<string>();

        for(let name in object) {
            if(this.isString(name))
                result.push(name);
        }
        
        return result;
    }

    public static getValues<T>(object : T) : Array<string | number> {
        let result = new Array<string | number>();

        for(let name in object) {
            if(this.isString(name))        
                result.push(<any>object[name]);
        }

        return result;
    }
}

Example:

enum Fruit {
    Apple,
    Orange,
    Cherry
}

console.log(EnumReflection.getNames(Fruit));
console.log(EnumReflection.getValues(Fruit));

Output:

[ 'Apple', 'Orange', 'Cherry' ]
[ 0, 1, 2 ]

Note: this logic can be used with string valued enums too.
e.g.

enum Fruit {
    Apple = 'Apple',
    Orange = 'Orange',
    Cherry = 'Cherry'
}
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