Named domain cases
Representing a finite domain such as direction, status, or mode.
TypeScript · Const
Enums define named constants and a type for a finite set of cases. TypeScript supports numeric, string, regular, and const enums, with regular enums available at runtime and const-enum members inlined during compilation.
An enum declaration creates a named set of constants and a corresponding type. Members may have constant or computed values; regular enums remain runtime objects, while const enums accept only constant enum expressions and are removed during compilation with member uses inlined.
enum EnumName {
Member [= value],
...
}
const enum EnumName {
Member [= constantValue],
...
}enum Direction {
Up = 1,
Down,
Left,
Right,
}
const direction: Direction = Direction.Down;
console.log(direction);Defines a numeric enum whose later members continue from the explicitly assigned value, then uses a member as a value and as the declared type.
Representing a finite domain such as direction, status, or mode.
Making intent explicit when values correspond to distinct alternatives.
Avoiding a generated runtime enum object when compile-time constants are sufficient.
An enum defines named constants and also creates a type with those members. Numeric enums can infer later values from an initialized numeric member, while string enums require explicit values.
Follow-up: How can you obtain the enum's member names as a type? Use keyof typeof Enum, because keyof applied directly to an enum does not produce the expected string-key union.
A regular enum is represented by a runtime object, so member access works in emitted JavaScript. A const enum is restricted to constant enum expressions, erased during compilation, and its members are substituted at use sites.
Follow-up: What trade-off follows from const-enum erasure? Code cannot rely on a const enum object existing at runtime.
Enum members may be constant or computed. Constant enum expressions can be evaluated during compilation; const enums are limited to those expressions, whereas regular enums can also contain computed members.
Follow-up: What happens after an enum member has a computed value? Subsequent uninitialized members cannot automatically continue unless the preceding value is a valid numeric constant context.
const enumnumeric enumsstring enumsenum memberskeyof typeof