Want a faster signal before interviews? Take the Interview Ready Check →

DAY 20 OF 30

Enums

Yesterday, in one sentence

What is a type assertion in TypeScript, and why would you use one?

Interview question

What is the difference between as const and as?

A literal unionLiteral Union restricts a value to a fixed set of options.

type Alignment = "hero" | "villain";

let side: Alignment = "hero";

An enum does the same job, but it also gives each option a name you refer to it by, instead of writing the raw value. You write it with the enum keyword, and the entries inside it are called members.

enum Alignment {
  Hero = "hero",
  Villain = "villain",
}

Alignment.Hero; // "hero"

The enum's name gives you two things. Alignment is an object holding those values, and it is also a type. Used as a type it accepts only its own members, and does not recognise the values attached to them.

let side: Alignment; // can be Alignment.Hero or Alignment.Villain

side = Alignment.Hero; // ok
side = Alignment.Villain; // ok
side = "villain"; // ❌ not assignable to type 'Alignment'

Everywhere else TypeScript uses structural typingStructural Typing: if it looks like a duck, it is a duck. Enums are the exception, and require the exact member rather than a matching value.

Because an enum is a value as well as a type, that object has to exist when the code runs. It is the one piece of TypeScript that is converted into JavaScript at build timeBuild Time rather than stripped out.

If you leave the values off, TypeScript numbers the members from zero instead.

enum Rank {
  Alpha, // 0
  Beta, // 1
}

Check yourself

Which of these produces JavaScript in the compiled output?
What is an enum in TypeScript?