Languages
[Edit]
EN

TypeScript - iterate enum

13 points
Created by:
Marcin
2477

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.

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.