ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

TypeScript Tutorial• 8 min read

Union, Intersection & Discriminated Unions

Exhaustive pattern matching and type guards with typeof, instanceof, and in

Type narrowing is the process by which TypeScript refines a broad type (like a union) into a more specific type within a conditional branch based on runtime checks.

Discriminated Unions: The Gold Standard for State

A Discriminated Union is a union where every member shares a common literal property (the "discriminant", e.g., kind or status).

typeof: Narrows primitives (string, number, boolean, symbol).

instanceof: Narrows class instances (Date, Error, custom classes).

in: Checks for property presence on an object shape.

Exhaustiveness checking: Using the never type in a default switch case guarantees compile errors if new union members are added without handling.

State Machine using Discriminated Unions
type AsyncState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: string };

function renderState(state: AsyncState<string[]>): string {
  switch (state.status) {
    case 'idle':
      return 'Click to load items.';
    case 'loading':
      return 'Fetching remote assets...';
    case 'success':
      // TypeScript knows state.data exists HERE only!
      return `Loaded ${state.data.length} items successfully.`;
    case 'error':
      // TypeScript knows state.error exists HERE only!
      return `Failed: ${state.error}`;
    default: {
      const _exhaustiveCheck: never = state;
      return _exhaustiveCheck;
    }
  }
}
TypeScript automatically narrows properties based on the status discriminant.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is a "discriminant" property in a Discriminated Union?