ProgrammingFullstack Developer

How does enum typing work in TypeScript, what types of enums exist, and what is the difference between constant and computed values? What pitfalls may arise when using enums?

Pass interviews with Hintsage AI assistant

Answer

TypeScript supports two types of enum:

  • Numeric — default values are assigned in order starting from 0.
  • String — each value must be explicitly defined, and it is a string.

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:

  • Numeric enums support reverse mapping enum → number → string-name.
  • String enums only support direct mapping (name → value).
  • Compilation errors occur when mixing types within the same enum.

Trick question

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).

Examples of real errors due to ignorance of the nuances of the topic.


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.