TypeScript Union and Literal Types

TypeScript union types let a value be one of several types, written with a vertical bar. Literal types narrow a type down to exact values, like "small" or 404. Together they model real data very precisely.

Union Types

A union value can only use members common to every type in the union, until you narrow it (next chapter).

type ID = number | string;

function showId(id: ID) {
  console.log("ID:", id);
}
showId(101);
showId("ORD-101");
// showId(true); // Error: 'boolean' is not assignable to 'ID'.
ID: 101
ID: ORD-101

Literal Types

A union of string literals is a lightweight, type-safe alternative to enums. Your editor autocompletes the allowed values.

type Size = "small" | "medium" | "large";
type Status = 200 | 404 | 500;

function orderCoffee(size: Size) {
  const prices = { small: 3, medium: 4.5, large: 6 };
  return prices[size];
}
console.log(orderCoffee("medium"));
// orderCoffee("huge"); // Error: '"huge"' is not assignable to type 'Size'.
const s: Status = 404;
console.log(s);
4.5
404

Optional Values with Unions

Combine a type with null or undefined to mark a value that may be missing. Strict mode forces you to handle that case.

function findEmail(id: number): string | undefined {
  const emails: Record<number, string> = { 1: "ali@example.com" };
  return emails[id];
}
const email = findEmail(2);
// email.toUpperCase(); // Error: 'email' is possibly 'undefined'.
console.log(email?.toUpperCase() ?? "not found");
not found

Intersection Types

An intersection (A & B) combines several types into one that has all their properties.

type HasId = { id: number };
type Timestamps = { createdAt: string; updatedAt: string };
type Post = HasId & Timestamps & { title: string };

const p: Post = { id: 1, title: "Hello TS", createdAt: "2026-01-01", updatedAt: "2026-02-01" };
console.log(p.id, p.title, p.updatedAt);
1 Hello TS 2026-02-01

Union vs Intersection

  • A | B: the value is A or B (either set of properties)
  • A & B: the value is both A and B (all properties)
  • Unions of literals replace most enums in modern TypeScript

Frequently asked questions

What is a union type in TypeScript?

A type that allows one of several types, written with |, such as string | number.

Should I use string literal unions or enums?

Many teams prefer literal unions because they have no runtime cost and work well with plain JSON data. Enums are fine when you want a named runtime object.

What is the difference between union and intersection types?

A union means "one of these types"; an intersection means "all of these types at once".