Course contentsShow
← TypeScript
Lesson 404 of 1,7969. Union TypesFree lesson

What Is a Discriminated Union?

A union of object types sharing a common literal property that distinguishes each variant.

What Is a Discriminated Union?

You'll learn how to use a shared literal property to make union types easier and safer to work with.

The Core Idea

A discriminated union (also called a "tagged union") is a union of object types where each variant has a common property with a distinct literal value. This shared property acts as a "tag" that lets TypeScript (and you) distinguish which variant you're working with.

Think of it like sorting mail: if every letter has a clear category stamp ("Personal," "Business," or "Junk"), you can instantly route it to the right pile without opening the envelope.

How It Works

Each object type in the union has the same property name, but with different literal type values. This property becomes the discriminant:

type Success = { status: "success"; data: string };
type Error = { status: "error"; message: string };
type Loading = { status: "loading" };

type ApiState = Success | Error | Loading;

Here, status is the discriminant property. Each variant has a unique literal value: "success", "error", or "loading".

Why This Matters

When you narrow on the discriminant property, TypeScript automatically knows which variant you're dealing with:

function handleState(state: ApiState) {
  if (state.status === "success") {
    // TypeScript knows: state is Success
    console.log(state.data);
  } else if (state.status === "error") {
    // TypeScript knows: state is Error
    console.log(state.message);
  }
}

The discriminant turns complex union narrowing into simple equality checks.

Key Takeaway: A discriminated union uses a shared property with distinct literal values to make union types predictable, safe, and easy to narrow—turning a union of objects into a clearly labeled set of variants.