Curriculum
Course: TypeScript
Login
Text lesson

TS Enums

An enum is a special “class” that represents a group of constants (unchangeable variables).

Enums come in two types: numeric and string. Let’s start with numeric.

Numeric Enums – Default

By default, enums initialize the first value to 0 and increment each subsequent value by 1.

Example

enum CardinalDirections {
  North,
  East,
  South,
  West
}
let currentDirection = CardinalDirections.North;
// logs 0
console.log(currentDirection);
// throws error as ‘North’ is not a valid enum
currentDirection = ‘North’// Error: “North” is not assignable to type ‘CardinalDirections’.

Numeric Enums – Initialized

You can specify the value of the first numeric enum and have the subsequent values auto-increment from that starting point.

Example

enum CardinalDirections {
  North = 1,
  East,
  South,
  West
}
// logs 1
console.log(CardinalDirections.North);
// logs 4
console.log(CardinalDirections.West);

Numeric Enums – Fully Initialized

You can assign unique number values to each enum member, which prevents automatic incrementation.

Example

enum StatusCodes {
  NotFound = 404,
  Success = 200,
  Accepted = 202,
  BadRequest = 400
}
// logs 404
console.log(StatusCodes.NotFound);
// logs 200
console.log(StatusCodes.Success);

String Enums

Enums can also contain strings, which is often preferred over numeric enums due to their readability and clarity of intent.

Example

enum CardinalDirections {
  North = ‘North’,
  East = “East”,
  South = “South”,
  West = “West”
};
// logs “North”
console.log(CardinalDirections.North);
// logs “West”
console.log(CardinalDirections.West);
Technically, you can mix string and numeric enum values, but it is generally recommended to avoid doing so.