Conditional & Mapped Types in React
Build component prop types that change shape based on other prop values using conditional types.
Conditional Types Basics
A conditional type uses T extends U ? X : Y syntax — if T is assignable to U, the type resolves to X, otherwise Y.
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
type C = IsString<'hello'>; // trueConditional Props Based on Other Props
Use conditional types to make a prop required or optional based on another prop's value.
type InputProps<T extends 'text' | 'number'> = {
type: T;
} & (T extends 'number' ? { min?: number; max?: number } : { maxLength?: number });
const numInput: InputProps<'number'> = { type: 'number', min: 0, max: 100 };
const txtInput: InputProps<'text'> = { type: 'text', maxLength: 50 };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