Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Typescript to iterate over a const enum?

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"}
];
like image 760
Jim Avatar asked Aug 29 '17 14:08

Jim


People also ask

Can you iterate over an enum TypeScript?

Use the Object. keys() or Object. values() methods to get an array of the enum's keys or values.

Can you iterate over enum?

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.

What is const enum TypeScript?

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.)

What is the difference between enum and const enum?

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.


1 Answers

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.

like image 198
JKillian Avatar answered Sep 17 '22 18:09

JKillian