Languages
[Edit]
EN

TypeScript - iterate enum

13 points
Created by:
Vanessa-Drake
718

In TypeScript it is possible to itererate enum members in followin way.

interface IIteration {
    (name : string, value : string | number) : void;
}

class EnumUtils {
    private static EXPRESSION = /^[0-9]+$/g;

    public static iterate<T>(type : T, iteration : IIteration) {

        for(let name in type) {
            if(name.match(this.EXPRESSION))
                continue;
    
            iteration(name, <any>type[name]);
        }
    }
}

Example:

enum Fruit {
    Apple,
    Orange,
    Cherry
}

enum Car {
    BMW = 'BMW',
    Ford = 'FORD',
    Porshe = 'PORSHE'
}

enum Digit {
    One = 1,
    Two = 2,
    Three = 3
}

let iteration = (name : string, value : string | number) : void => {
    console.log(`${name} : ${value}`);
};

EnumUtils.iterate(Fruit, iteration);
EnumUtils.iterate(Car, iteration);
EnumUtils.iterate(Digit, iteration);

// or just:
// EnumUtils.iterate(Fruit, console.log);
// EnumUtils.iterate(Car, console.log);
// EnumUtils.iterate(Digit, console.log);

Output:

Apple : 0
Orange : 1
Cherry : 2

BMW : BMW
Ford : FORD
Porshe : PORSHE

One : 1
Two : 2
Three : 3

Run it online here.

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