0Pricing
TypeScript Academy · Lesson

Discriminated Unions for Safe Pattern Matching

Add a common literal field to union members for type safety.

Welcome

Discriminated unions add a shared literal property to union members. TypeScript uses this discriminant to narrow the type in switch and if statements.

The Discriminant Property

A discriminant is a property with a unique literal type in each union member. TypeScript narrows the union based on its value.
type Circle = { kind: 'circle'; radius: number };
type Square = { kind: 'square'; side: number };
type Shape = Circle | Square;

All lessons in this course

  1. Union Types: A or B
  2. Intersection Types: A and B
  3. Discriminated Unions for Safe Pattern Matching
  4. Practical Patterns with Union and Intersection
← Back to TypeScript Academy