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

Multiple Discriminants in One Union

Using more than one property as discriminants when variants differ in multiple ways.

Multiple Discriminants in One Union

What you'll learn: How to use more than one property to distinguish between variants when they differ in multiple meaningful ways.

Why Multiple Discriminants?

So far, you've seen unions narrowed by a single discriminant property (like type or kind). But sometimes variants naturally differ across multiple dimensions, and using several discriminant properties can make your code more expressive and easier to narrow.

The Core Idea

A discriminated union can have more than one property serving as a discriminant. Each property independently helps TypeScript narrow the union, and you can use any combination of them to identify the exact variant.

Think of it like sorting mail: sometimes you need both the country and the postal code format to know what you're dealing with. Each piece of information narrows down the possibilities.

How It Works

When TypeScript sees you check multiple properties, it tracks which variants remain possible after each check. The narrowing compounds:

type Event =
  | { category: "user"; action: "login"; userId: string }
  | { category: "user"; action: "logout"; userId: string }
  | { category: "system"; action: "restart"; code: number }
  | { category: "system"; action: "shutdown"; code: number };

function handle(event: Event) {
  if (event.category === "user") {
    // Narrowed to first two variants
    console.log(event.userId); // OK
  }

  if (event.action === "login") {
    // Narrowed to first variant only
    console.log(event.userId); // OK
  }

  if (event.category === "system" && event.action === "restart") {
    // Narrowed to exact variant
    console.log(event.code);
  }
}

Both category and action act as discriminants. You can check either one, or both together, depending on what you need to know.

Key Takeaway: Discriminated unions can use multiple properties as discriminants, allowing you to narrow based on whichever combination of checks makes sense for your logic.