EN
TypeScript - iterate enum
13 points
In TypeScript it is possible to itererate enum
members in followin way.
xxxxxxxxxx
1
interface IIteration {
2
(name : string, value : string | number) : void;
3
}
4
5
class EnumUtils {
6
private static EXPRESSION = /^[0-9]+$/g;
7
8
public static iterate<T>(type : T, iteration : IIteration) {
9
10
for(let name in type) {
11
if(name.match(this.EXPRESSION))
12
continue;
13
14
iteration(name, <any>type[name]);
15
}
16
}
17
}
Example:
xxxxxxxxxx
1
enum Fruit {
2
Apple,
3
Orange,
4
Cherry
5
}
6
7
enum Car {
8
BMW = 'BMW',
9
Ford = 'FORD',
10
Porshe = 'PORSHE'
11
}
12
13
enum Digit {
14
One = 1,
15
Two = 2,
16
Three = 3
17
}
18
19
let iteration = (name : string, value : string | number) : void => {
20
console.log(`${name} : ${value}`);
21
};
22
23
EnumUtils.iterate(Fruit, iteration);
24
EnumUtils.iterate(Car, iteration);
25
EnumUtils.iterate(Digit, iteration);
26
27
// or just:
28
// EnumUtils.iterate(Fruit, console.log);
29
// EnumUtils.iterate(Car, console.log);
30
// EnumUtils.iterate(Digit, console.log);
Output:
xxxxxxxxxx
1
Apple : 0
2
Orange : 1
3
Cherry : 2
4
5
BMW : BMW
6
Ford : FORD
7
Porshe : PORSHE
8
9
One : 1
10
Two : 2
11
Three : 3
Run it online here.