Menu

Discriminated Unions and Exhaustive Checks

Lesson 3: Discriminated Unions and Exhaustive Checks

What is a discriminated union?

A discriminated (or tagged) union is a union of object types that share one literal property, such as status or kind. Checking that property tells TypeScript exactly which member you have.

Without a discriminant With a discriminant
Many optional fields, unclear which go together Each state has exactly the fields it needs
if ('trackingId' in order) checks switch (order.status)
Impossible combinations allowed Impossible combinations rejected

Example

type Order =
  | { status: 'pending'; placedAt: Date }
  | { status: 'shipped'; placedAt: Date; trackingId: string; courier: string }
  | { status: 'delivered'; placedAt: Date; deliveredAt: Date }
  | { status: 'cancelled'; placedAt: Date; reason: string };

function orderMessage(order: Order): string {
  switch (order.status) {
    case 'pending':
      return 'We are packing your order.';
    case 'shipped':
      return `On the way with ${order.courier} (${order.trackingId}).`;
    case 'delivered':
      return `Delivered on ${order.deliveredAt.toLocaleDateString('en-IN')}.`;
    case 'cancelled':
      return `Cancelled: ${order.reason}`;
    default: {
      const unhandled: never = order;
      throw new Error(`Unhandled status: ${JSON.stringify(unhandled)}`);
    }
  }
}

How it works

  • In each case, TypeScript narrows order to the matching member, so trackingId is available only for 'shipped'.
  • In default, every member has been ruled out, so order is never.
  • If someone adds { status: 'returned'; ... } to Order, assigning it to never fails to compile, pointing to every switch that must handle the new state. This is an exhaustive check.

The same pattern models API results:

type Result<T> = { ok: true; data: T } | { ok: false; error: string };

Common mistakes

Mistake Effect Fix
Discriminant typed as string instead of literals No narrowing Use literal types like 'shipped'
No default with never New states silently fall through Add the exhaustive check
Destructuring the discriminant into a separate variable early Narrowing may not apply to the object Switch on order.status directly

Key takeaways

  • Discriminated unions make invalid states impossible to represent.
  • A never check in default turns forgotten cases into compile errors.

Try it: Model a PaymentState union (idle, processing, success with a transaction ID, failed with an error message) and write an exhaustive renderPaymentState function.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details