Languages
[Edit]
EN

TypeScript - convert enum to array

12 points
Created by:
Root-ssh
116170

In this article, we would like to show how to to get enum names or values in TypeScript.

Warning: some tools may remove information about enums during source code optimization that makes impossible to extract enum names and valies - e.g. preact-cli during production bundle building.

Custom enum reflection example

In this section, you can find reusable util that helps to extract data from the enum.

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

    private static isString(name: string): boolean {
        if (name.match(this.REGEXP)) {
            return false;
        }
        return true;
    }

    public static getNames(object: Record<string, string | number>): Array<string> {
        const result = new Array<string>();
        for (let name in object) {
            if (this.isString(name)) {
                result.push(name);
            }
        }
        return result;
    }

    public static getValues(object: Record<string, string | number>): Array<string | number> {
        const result = new Array<string | number>();
        for (let name in object) {
            if (this.isString(name)) {
                result.push(object[name] as any);
            }
        }
        return result;
    }
}


// Usage example:

enum Fruit {
    Apple,
    Orange,
    Cherry
}

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

Output:

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

Note: the above logic can be used with string valued enums too, e.g.

enum Fruit {
    Apple = 'Apple',
    Orange = 'Orange',
    Cherry = 'Cherry'
}

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

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join