Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

TypeScript - iterate enum

0 contributions
13 points

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.

0 contributions

Suggested wiki articles:

Suggested findings

Let's do the work and have some fun
  • Dirask is online IT community for professionals and hobbyist 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,
    we will help you. 👍 ✔ 🦄
Read more