Sobes.tech
Middle

Do you know the difference between enum and constants in TypeScript?

sobes.tech AI

Answer from AI

In TypeScript, enum is a special type that allows creating a set of named constants, which can be either numeric or string. They are compiled into an object with reverse mapping (number ↔ name), enabling their use as values and keys.

Constants (const) are simply immutable variables that can hold any value, including primitives, objects, or functions. They do not have reverse mapping and do not create a separate type.

Main differences:

  • enum creates its own type with a set of fixed values, which is convenient for a limited set of options.
  • const is just an immutable variable, does not create a type, and has no reverse mapping.
  • During compilation, enum generates an object, whereas const just becomes a variable.

Example of enum:

enum Direction {
  Up = 1,
  Down,
  Left,
  Right
}

let dir: Direction = Direction.Up;

Example of constants:

const UP = 1;
const DOWN = 2;
const LEFT = 3;
const RIGHT = 4;

let dir = UP;

If you need typing and ease of working with a set of values, it's better to use an enum. If you just need a set of values without a type, constants are sufficient.