Borislav Hadzhiev
Mon Feb 14 2022·2 min read
Photo by Meiying Ng
To get all enum values as an array, pass the enum to the Object.values()
method, e.g. const values = Object.values(StringEnum)
. The Object.values
method will return an array of the enum's values, because enums in TypeScript
are real objects and exist at runtime.
// ✅ For STRING Enums enum StringEnum { Small = 'S', Medium = 'M', Large = 'L', } const values1 = Object.values(StringEnum); // 👇️ ['S', 'M', 'L'] console.log(values1); const keys1 = Object.keys(StringEnum); // 👇️ ['Small', 'Medium', 'Large'] console.log(keys1); // ✅ For NUMERIC Enums enum NumericEnum { Small, Medium, Large, } const values2 = Object.keys(NumericEnum).filter((v) => !isNaN(Number(v))); console.log(values2); // 👉️ ['0', '1', '2'] const keys2 = Object.keys(NumericEnum).filter((v) => isNaN(Number(v))); console.log(keys2); // 👉️ ['Small', 'Medium', 'Large']
Enums are real objects in TypeScript and exist at runtime. This is why we are able to use the Object.values method to get an array containing the enum's values.
The Object.values()
method returns an array containing an object's values.
// 👇️ ['Tom', 30] console.log(Object.values({ name: 'Tom', age: 30 }));
However the output for numeric and string enums is different.
// ✅ For STRING Enums enum StringEnum { Small = 'S', Medium = 'M', Large = 'L', } // 👇️ ['S', 'M', 'L'] console.log(Object.values(StringEnum)); // ✅ For NUMERIC Enums enum NumericEnum { Small, Medium, Large, } // 👇️ ['Small', 'Medium', 'Large', 0, 1, 2] console.log(Object.values(NumericEnum));
Notice that when a numeric enum is passed to the Object.values()
method, the
enum keys and values are returned.
We haven't provided an initial value for the numeric enum, so its values start
at 0
and auto increment.
This is why we had to filter out the unnecessary keys in the examples above.
If you need to iterate over the array of enum values, you can use a for...of
loop or the Array.forEach
method.
enum StringEnum { Small = 'S', Medium = 'M', Large = 'L', } const values1 = Object.values(StringEnum); // 👇️ ['S', 'M', 'L'] console.log(values1); for (const v of values1) { console.log(v); // 👉️ S, M, L } values1.forEach((v, index) => { console.log(v); // 👉️ S, M, L });
Note that the examples above would not work if you use const enums, because const enums can only use constant enum expressions and are completely removed during compilation.