TypeScript supports two types of enum:
There are also heterogeneous enums (mixed types), but their use is highly discouraged.
Example:
enum Status { Init, Loading, Ready = 5, Error } // Status.Error === 6 enum HttpCode { Ok = 200, NotFound = 404, Internal = 'INTERNAL_ERROR' // Error! Either only strings or only numbers } enum Direction { Up = 'UP', Down = 'DOWN', }
Constant values are calculated at compile time. If an ENUM value depends on other calculations or expressions (e.g., a function), it becomes a computed value (computed member). Only previous enum members can be used to calculate the current member as a default value.
Important features:
Can you use the value of another enum when declaring a member of a new enum?
Answer: Yes, but only if that value is a constant or a member declared earlier.
Example:
enum A { X = 1 } enum B { Y = A.X } // OK
However, you cannot use computations based on functions or data from other places (e.g., function calls).
Story
In a project for serializing data to an external API, a numeric enum was used. When the order of the enum members changed, the values "shifted," and external systems began receiving different numbers. This led to incorrect states in external clients, which were impossible to track without code auditing.
Story
In one React project, a string and numeric enum were mistakenly used in a switch-case, expecting that values would be coerced to strings. Due to the mismatch, the switch did not work correctly, and the component returned an invalid UI.
Story
When trying to create an enum where some values are computed through a function, TypeScript did not throw errors, but in some builds, the values turned out to be undefined. This led to routing issues when the enum was used as an identifier for paths. A critical error only reproduced in production bundles.