πŸŽ›οΈ Enums in TypeScript

What are enums?

Enums are programming constructs that allow you to represent a set of constants that belong to a particular context.

enum Direction {
  UP,
  DOWN,
  LEFT,
  RIGHT,
}

enum State {
  LOADING,
  SUCCESS,
  ERROR,
}

Why are they useful?

They are useful because they allow the programmer to define and use these constants in an easy and meaningful way, improving the readability of the code.

moveCharacter(Direction.DOWN);

setState(State.LOADING);

The compiler will ensure that all the values of the enum are the same everywhere where they are used.

Numeric enums

If nothing is specified, TypeScript will assign numeric values to the enums. By default, TypeScript will start with 0 and auto increment it, but you can change the starting number:

enum State {
  LOADING, // By default will be 0
  SUCCESS, // 1
  ERROR, // 2
}
enum State {
  LOADING = 1, // It will be 1
  SUCCESS, // 2
  ERROR, // 3
}

String enums

You can also assign strings to your enum members, they will be the values used in runtime.

enum Status {
  LOADING = 'LOADING',
  SUCCESS = 'SUCCESS',
  ERROR = 'ERROR',
}

The main benefit is that you don’t rely on the member position and you lock the value that will be later used up/down stream and stored in the database.

Enums as types

Enums can be used as any other type in TypeScript: as the type of a field of an object, as the input type of a variable in a function, etc.

// Using enums in other types:
type Player = {
  direction: Direction,
  health: number,
}

// Using enums in functions:
function updateDirection(player: Player, newDirection: Direction) {
  ...
}

Compiling enums

So how are enums compiled into JavaScript? They get converted to objects whose keys are the enums members and the values the numeric or string values you gave them:

// The State enum with string members would be compiled into this:
const State = {
  LOADING: 'LOADING',
  SUCCESS: 'SUCCESS',
  ERROR: 'ERROR',
};