0Pricing
React Academy · Lesson

Discriminated Unions for Component Variants

Model variant props with discriminated unions so TypeScript enforces valid prop combinations.

The Problem with Variant Props

A component with optional props for different modes (e.g., a button that's either a link or a button) can have invalid prop combinations. TypeScript can't catch them without discriminated unions.

What Is a Discriminated Union?

A discriminated union is a union of types that share a common literal type field (the discriminant). TypeScript narrows the type based on that field's value.

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'rectangle'; width: number; height: number };

function area(shape: Shape): number {
  if (shape.kind === 'circle') return Math.PI * shape.radius ** 2;
  return shape.width * shape.height; // TS knows width/height exist here
}

All lessons in this course

  1. Discriminated Unions for Component Variants
  2. Conditional & Mapped Types in React
  3. Polymorphic Components with 'as' Prop
  4. Type-Safe Forms & API Response Contracts
← Back to React Academy