Similar to this question, but with the enumeration marked as a constant: How do you go about iterating or producing an array of from the const enum?
Example
declare const enum FanSpeed {
Off = 0,
Low,
Medium,
High
}
Desireable Results
type enumItem = {index: number, value: string};
let result: Array<enumItem> = [
{index: 0, value: "Off"},
{index: 1, value: "Low"},
{index: 2, value: "Medium"},
{index: 3, value: "High"}
];
Use the Object. keys() or Object. values() methods to get an array of the enum's keys or values.
Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.
A const Enum is the same as a normal Enum. Except that no Object is generated at compile time. Instead, the literal values are substituted where the const Enum is used. // Typescript: A const Enum can be defined like a normal Enum (with start value, specifig values, etc.)
Const enums can only use constant enum expressions and unlike regular enums they are completely removed during compilation. Const enum members are inlined at use sites. This is possible since const enums cannot have computed members.
No, this is not possible with a const enum
. Let's start with your original enum and log one of its values:
const enum FanSpeed {
Off = 0,
Low,
Medium,
High
}
console.log(FanSpeed.High);
The TypeScript compiler inlines all the references to FanSpeed
, and compiles the above code into something like this:
console.log(3 /* High */);
In other words, since you're using a const enum
, no FanSpeed
object actually exists at run time, just simple numeric literals are passed around instead. With a regular, non-const enum
, a FanSpeed
would exist as a value and you could iterate over its keys.
Edit: If you can change the compiler settings of your project, see Titian's answer below for very useful information about the preserveConstEnums
flag, which will cause a FanSpeed
object to actually be created and thus give you a way to iterate over your enum.
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