Languages
[Edit]
EN

TypeScript - convert enum to array

12 points
Created by:
Root-ssh
68500

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'
}
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join