0PricingLogin
React Academy · Lesson

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'>; // true

Conditional 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

  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