CPCODELAB
TypeScript

Union & Intersection Types

9 min read

Union & Intersection Types

Union types

A union type (A | B) means a value can be either A or B. Union types are extremely common — any time a value might be one of several shapes, a union is the right tool.

ts
type Status = "pending" | "active" | "cancelled";

function formatId(id: string | number): string {
  if (typeof id === "number") {
    return id.toFixed(0);
  }
  return id.trim();
}

Intersection types

An intersection type (A & B) means a value must satisfy both A and B simultaneously. It combines object shapes — the result has all properties of both types.

ts
type Timestamped = { createdAt: Date; updatedAt: Date };
type Tagged = { tags: string[] };

type Article = { title: string; body: string } & Timestamped & Tagged;

const post: Article = {
  title: "Hello world",
  body: "Content here",
  createdAt: new Date(),
  updatedAt: new Date(),
  tags: ["typescript", "tutorial"]
};

Intersecting two primitive types (like string & number) creates never, because no value can be both a string and a number at once. Intersections are most useful with object shapes.

Ready to test yourself?
Practice TypeScript— quiz & coding exercises