9.1 Enum Declarations
An enum declaration declares an enum type and an enum object.
EnumDeclaration: const
opt enum
BindingIdentifier {
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
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
var Color: {
[x: number]: string;
Red: Color;
Green: Color;
Blue: Color;
};
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
var c = Color.Red;
console.log(Color[c]); // Outputs "Red"