Languages
[Edit]
EN

TypeScript - convert enum to array

12 points
Created by:
Root-ssh
177780

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

Quick solution:

enum Fruit {
    Apple,
    Orange,
    Cherry = 'cherry',
    Banana = 'banana'
}

const keys = Object.keys(Fruit);

const names = keys.filter(key => !/^[0-9]+$/.test(key));  // ['Apple', 'Orange', 'Cherry', 'Banana']
const values = names.map(key => Fruit[key as any]);       // [0, 1, 'cherry', 'banana']

Note: runnable example is available here.

 

Reusable code

The example contains reusable util that helps to extract data from the enums.

class EnumUtils {

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

    public static getEntities<V extends string | number>(object: Record<string, string | number>, converter: (name: string) => V): Array<V> {
        const result = new Array<V>();
        for (let name in object) {
            if (!this.REGEXP.test(name)) {
                result.push(converter(name));
            }
        }
        return result;
    }

    public static getNames(object: Record<string, string | number>): Array<string> {
        return this.getEntities(object, name => name);
    }

    public static getValues(object: Record<string, string | number>): Array<string | number> {
        return this.getEntities(object, name => object[name]);
    }
}


// Usage example:

enum Fruit {
    Apple,
    Orange,
    Cherry = 'cherry',
    Banana = 'banana'
}

console.log(EnumUtils.getNames(Fruit));   // ['Apple', 'Orange', 'Cherry', 'Banana']
console.log(EnumUtils.getValues(Fruit));  // [0, 1, 'cherry', 'banana']

Note: runnable example is available here.

Output:

['Apple', 'Orange', 'Cherry', 'Banana']
[0, 1, 'cherry', 'banana']

 

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

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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