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
- Discriminated Unions for Component Variants
- Conditional & Mapped Types in React
- Polymorphic Components with 'as' Prop
- Type-Safe Forms & API Response Contracts