Enums | Typescript
Definition and types#
Computed and constant members#
Enums at runtime#
Enums are real objects that exist at runtime.
Enums at compile time#
Even though Enums are real objects that exist at runtime, the keyof keyword works differently than you might expect for typical objects. Instead, use keyof typeof to get a Type that represents all Enum keys as strings.
Reverse mappings#
Numeric enums members also get a reverse mapping from enum values to enum names.
Keep in mind that string enum members do not get a reverse mapping generated at all.
const enums#
To avoid paying the cost of extra generated code and additional indirection when accessing enum values, it's possible to use const enums.
Const enums are defined using the const modifier on our enums:
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.
in generated code will become
Ambient enums#
Ambient enums are used to describe the shape of already existing enum types.
"declare" or "ambient"
In TypeScript, you can "declare" things that the compiler should know about, but not actually emit code for. This is useful when you have libraries like jQuery that define some object (e.g. $) that you want type information about, but don't need any code created by the compiler. The spec and other documentation refers to declarations made this way as being in an "ambient" context; it is important to note that all declarations in a .d.ts file are "ambient" (either requiring an explicit declare modifier or having it implicitly, depending on the declaration type).
One important difference between ambient and non-ambient enums is that, in regular enums, members that don't have an initializer will be considered constant if its preceding enum member is considered constant. In contrast, an ambient (and non-const) enum member that does not have initializer is always considered computed.