Join my Vue.js course while it's free 👀

Enums in TypeScript

June 19, 2022  ‐ 1 min read

Enums, short for enumerated types, are data structures containing a collection of named constants. For these named constants you don't need to assign an underlying value yourself, this is handled by TypeScript.

To define an enum we start with the enum keyword followed by the name we wish to use for the enum. Between braces we define the types that make up the enum.

enum State {
  Loading,
  Error,
  Success,
}

The advantage of using enums in our code is that we don't have to come up with arbitrary values for constants by ourselves. TypeScript abstracts this away, so that we can use just a readable enum.

application.state = State.Loading;

// ...

if (application.state === State.Loading) {
  showSpinner();
}