9.4 Constant Enum Declarations

An enum declaration that specifies a const modifier is a constant enum declaration. In a constant enum declaration, all members must have constant values and it is an error for a member declaration to specify an expression that isn’t classified as a constant enum expression.

Unlike regular enum declarations, constant enum declarations are completely erased in the emitted JavaScript code. For this reason, it is an error to reference a constant enum object in any other context than a property access that selects one of the enum’s members. For example:

  1. const enum Comparison {
  2. LessThan = -1,
  3. EqualTo = 0,
  4. GreaterThan = 1
  5. }
  6. var x = Comparison.EqualTo; // Ok, replaced with 0 in emitted code
  7. var y = Comparison[Comparison.EqualTo]; // Error
  8. var z = Comparison; // Error

The entire const enum declaration is erased in the emitted JavaScript code. Thus, the only permitted references to the enum object are those that are replaced with an enum member value.