How do computed and constant enum members work when mixing string and numeric-style initialization?
Short answer
Enum members can be constant (a literal, or computed from prior members) or 'computed' (derived from a non-constant expression) — TypeScript requires that any UNINITIALIZED member following a computed one must have an explicit value, since it can no longer safely auto-increment…
Advertisement
AModel answer
Enum members can be constant (a literal, or computed from prior members) or 'computed' (derived from a non-constant expression) — TypeScript requires that any UNINITIALIZED member following a computed one must have an explicit value, since it can no longer safely auto-increment from an unknown runtime expression.
function getValue() { return 10; }
enum Mixed {
A = 1,
B = getValue(), // computed
// C would need an explicit value here -- can't auto-increment after a computed member
C = 20
}Real-world example
Rarely needed directly, but useful to understand when debugging why TypeScript demands an explicit value after certain enum members.
Likely follow-ups
- Why does TypeScript enforce this restriction specifically after computed members?
Related topics