9.1 Enum Declarations

An enum declaration declares an enum type and an enum object.

  EnumDeclaration:   constoptenumBindingIdentifier{EnumBodyopt}

An EnumDeclaration introduces a named type (the enum type) and a named value (the enum object) in the containing declaration space. The enum type is a distinct subtype of the Number primitive type. The enum object is a value of an anonymous object type containing a set of properties, all of the enum type, corresponding to the values declared for the enum type in the body of the declaration. The enum object’s type furthermore includes a numeric index signature with the signature ‘[x: number]: string’.

The BindingIdentifier of an enum declaration may not be one of the predefined type names (section 3.8.1).

When an enum declaration includes a const modifier it is said to be a constant enum declaration. The members of a constant enum declaration must all have constant values that can be computed at compile time. Constant enum declarations are discussed in section 9.4.

The example

  1. enum Color { Red, Green, Blue }

declares a subtype of the Number primitive type called ‘Color’ and introduces a variable ‘Color’ with a type that corresponds to the declaration

  1. var Color: {
  2. [x: number]: string;
  3. Red: Color;
  4. Green: Color;
  5. Blue: Color;
  6. };

The numeric index signature reflects a “reverse mapping” that is automatically generated in every enum object, as described in section 9.5. The reverse mapping provides a convenient way to obtain the string representation of an enum value. For example

  1. var c = Color.Red;
  2. console.log(Color[c]); // Outputs "Red"