Given an a TypeScript enum:
export enum Color { Red, Green, Blue, }
I want to get all its values in an array like so:
["Red", "Green", "Blue"]
Yet when I work on that enum with
const colors = Object.keys(Color);
I get weird array consisting of its index and value:
[ '0', '1', '2', 'Red', 'Green', 'Blue' ]
Why is this the case and how can I only get the values?
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.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
Iterating over the keys Of course, it's also possible to loop over the keys of a string enum, using Object.
You have to filter out the numeric keys, either via Object.values
or Object.keys
:
const colors = Object.keys(Color).filter((item) => { return isNaN(Number(item)); }); console.log(colors.join("\n"));
This will print:
Red Green Blue
A TypeScript enum will transpile in the end into a plain JavaScript object:
{ '0': 'Red', '1': 'Green', '2': 'Blue', Red: 0, Green: 1, Blue: 2 }
So you can use the numeric index as key to get the value, and you can use the value to lookup its index in the enum:
console.log(Color[0]); // "Red" console.log(Color["0"]); // "Red" console.log(Color["Red"]) // 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With