Is it possible in Typescript to iterate over a const enum?
You can use the preserveConstEnums
compiler flag. This will emit the enum object in the Javascript but replace all values. The problem is that you can't for
over the properties in a simple way because Typescript generates an error (enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment.
). There are ways to get around it but it depends on your environment.
Using modules you could write it like this:
import * as e from "./enumModule"
for(var prop in (e as any)['FanSpeed']) {
console.log(prop) ;
}
Or using a namespace you could do it like this:
namespace Enums {
export const enum FanSpeed {
Off = 0,
Low,
Medium,
High
}
}
for(var prop in (Enums as any)['FanSpeed']) {
console.log(prop) ;
}
Note: In either case you must use the preserveConstEnums compiler option first,
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.