Enums vs Unions

Two ways to say 'pick from this list'

8 min read

Another tool for fixed sets of options

You have already met literal unions like 'small' | 'medium' | 'large'. TypeScript has a second, older tool for the same job: the enum, short for enumeration. An enum is a named group of constants:

enum OrderStatus {
  Pending = 'PENDING',
  Shipped = 'SHIPPED',
  Delivered = 'DELIVERED'
}

let status: OrderStatus = OrderStatus.Shipped;

You refer to values through the enum name, like OrderStatus.Shipped, and the variable can only hold one of the members. Trying status = 'SHIPPED'; directly is an error; with an enum you must go through the enum itself.

The same idea as a union

Here is the equivalent written as a literal union:

type OrderStatus = 'pending' | 'shipped' | 'delivered';

let status: OrderStatus = 'shipped';

Both versions stop invalid values, both autocomplete nicely in editors, and both make your intent obvious. So which should you use?

How they differ

  • Enums generate real JavaScript. Remember that types are erased at compile time? Enums are the exception. An enum compiles into an actual JavaScript object that ships to the browser. A union is purely a type and produces zero output.
  • Unions use plain strings. With a union, the value in your code, in your JSON, and in your database is just 'shipped'. With enums there is an extra layer of indirection through OrderStatus.Shipped.
  • Enums group related constants under one name, which some teams find tidier, especially when the same set is used in many files.

Which one should a beginner reach for?

Most modern TypeScript style guides lean toward literal unions for everyday code. They are lighter, they add nothing to your compiled JavaScript, and they play perfectly with data from APIs, which arrives as plain strings anyway. Checking a union value works with ordinary comparisons:

function describe(status: OrderStatus): string {
  if (status === 'delivered') {
    return 'Your package has arrived!';
  }
  return 'On its way: ' + status;
}

Enums are not wrong, and you will meet them in existing codebases, so it is important to recognize the syntax. But when you are the one choosing, a union of literals is usually the simpler, more idiomatic pick.

Rule of thumb: start with a literal union. Reach for an enum only if your team already uses them or you specifically want a named object of constants in the compiled output.

Quick check

Q1 What is one real difference between an enum and a literal union?

Q2 For everyday beginner code, which choice do most modern style guides suggest?

Want to save your progress? It's free.

Create a free account