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

Nested Discriminated Unions

Composing unions where some variants themselves contain nested discriminated unions.

Nested Discriminated Unions

What you'll learn: How to compose discriminated unions where some variants themselves contain nested discriminated unions.

As your application grows, you'll often find that some branches of a discriminated union need their own internal variants. This is where nested discriminated unions come in—unions within unions.

The Core Idea

Sometimes a single discriminant property isn't enough. Imagine modeling an API response where success cases can have different data shapes, or error cases can have different error types. You create an outer discriminated union, but then within one or more variants, you introduce another discriminated union.

How It Works

type Success = 
  | { status: 'success'; kind: 'user'; name: string }
  | { status: 'success'; kind: 'product'; price: number };

type Error = 
  | { status: 'error'; code: 404; message: string }
  | { status: 'error'; code: 500; details: string[] };

type ApiResponse = Success | Error;

Here, ApiResponse is the outer union (discriminated by status). But both Success and Error are themselves discriminated unions—Success uses kind, and Error uses code.

Narrowing Nested Unions

You narrow in stages:

function handle(response: ApiResponse) {
  if (response.status === 'success') {
    // Narrowed to Success
    if (response.kind === 'user') {
      console.log(response.name); // user variant
    } else {
      console.log(response.price); // product variant
    }
  } else {
    // Narrowed to Error
    if (response.code === 404) {
      console.log(response.message);
    } else {
      console.log(response.details);
    }
  }
}

First you narrow by status, then by the inner discriminant.

Key Takeaway: Nested discriminated unions let you model complex, hierarchical state by layering unions within unions—each level uses its own discriminant property for safe, stepwise narrowing.