EN
TypeScript - convert enum to array
12 points
In this article, we would like to show how to to get enum names or values in TypeScript.
Quick solution:
xxxxxxxxxx
1
enum Fruit {
2
Apple,
3
Orange,
4
Cherry = 'cherry',
5
Banana = 'banana'
6
}
7
8
const keys = Object.keys(Fruit);
9
10
const names = keys.filter(key => !/^[0-9]+$/.test(key)); // ['Apple', 'Orange', 'Cherry', 'Banana']
11
const values = names.map(key => Fruit[key as any]); // [0, 1, 'cherry', 'banana']
Note: runnable example is available here.
The example contains reusable util that helps to extract data from the enums.
xxxxxxxxxx
1
class EnumUtils {
2
3
private static REGEXP : RegExp = /^[0-9]+$/;
4
5
public static getEntities<V extends string | number>(object: Record<string, string | number>, converter: (name: string) => V): Array<V> {
6
const result = new Array<V>();
7
for (let name in object) {
8
if (!this.REGEXP.test(name)) {
9
result.push(converter(name));
10
}
11
}
12
return result;
13
}
14
15
public static getNames(object: Record<string, string | number>): Array<string> {
16
return this.getEntities(object, name => name);
17
}
18
19
public static getValues(object: Record<string, string | number>): Array<string | number> {
20
return this.getEntities(object, name => object[name]);
21
}
22
}
23
24
25
// Usage example:
26
27
enum Fruit {
28
Apple,
29
Orange,
30
Cherry = 'cherry',
31
Banana = 'banana'
32
}
33
34
console.log(EnumUtils.getNames(Fruit)); // ['Apple', 'Orange', 'Cherry', 'Banana']
35
console.log(EnumUtils.getValues(Fruit)); // [0, 1, 'cherry', 'banana']
Note: runnable example is available here.
Output:
xxxxxxxxxx
1
['Apple', 'Orange', 'Cherry', 'Banana']
2
[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.