Languages
[Edit]
EN

TypeScript - convert enum to array

12 points
Created by:
Root-ssh
6322

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'
}
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.