0Pricing
TypeScript Academy · Lesson

Building Discriminated Unions

Tag union members with a shared discriminant property.

What Is a Discriminated Union?

A discriminated union is a union of object types that all share a common literal property called the discriminant. That shared tag lets TypeScript tell the members apart.

// The shared "kind" property is the discriminant
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;

The Discriminant Property

The discriminant must be a literal type (like "circle"), not a wide type like string. Each member gets its own unique literal value.

type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };

const c: Circle = { kind: "circle", radius: 10 };
console.log(c.kind); // "circle"

All lessons in this course

  1. Building Discriminated Unions
  2. Narrowing on the Discriminant
  3. Exhaustiveness Checking with never
  4. Modeling State Machines
← Back to TypeScript Academy