Discriminated Unions

What

A discriminated union (or “tagged union”) is a union of object types where each type has a shared property with a unique literal value, known as a discriminant.

How

By checking the discriminant property, TypeScript can narrow the union to one specific object type:

type MultipleChoice = { kind: "mc"; question: string; answer: string; };
type Coding = { kind: "code"; studentCode: string; };

type Lesson = MultipleChoice | Coding;

function check(lesson: Lesson) {
  switch (lesson.kind) {
    case "mc":
      // lesson is now MultipleChoice
      return lesson.answer;
    case "code":
      // lesson is now Coding
      return lesson.studentCode;
  }
}

Why

Discriminated unions are extremely useful for modeling complex states (like API responses or UI components). They allow the compiler to ensure you’ve handled every possible variation of a type, preventing runtime errors when accessing properties that only exist on specific branches of a union.

Summary

Use a shared property like kind or type to distinguish between different object structures within a single union.