Sobes.tech
Junior — Middle

Explain what enumerable types (enum) are in TypeScript and how they are used.

sobes.tech AI

Answer from AI

In TypeScript, enumerated types (enums) are a way to define a set of named constants, which can be either numeric or string. They help make code more readable and safe by restricting the variable's values to a specific set.

Example of a numeric enum:

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

let move: Direction = Direction.Up;

Here, Down will automatically have the value 2, Left will be 3, and so on.

Example of a string enum:

enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

let c: Color = Color.Green;

Enums simplify working with fixed sets of values and help avoid errors related to using "magic" numbers or strings.

Explain what enumerable types (enum) are in… - sobes.tech