0Pricing
React Academy · Lesson

Conditional & Mapped Types in React

Build component prop types that change shape based on other prop values using conditional types.

Conditional & Mapped Types in React is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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 };

Mapped Types

Mapped types create a new type by transforming each property of an existing type. The in keyof syntax iterates over all keys.

type Optional<T> = { [K in keyof T]?: T[K] };
type Readonly<T> = { readonly [K in keyof T]: T[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };

Making Props Optional for Update Forms

Use Partial<T> (a built-in mapped type) for update form props where not all fields are required.

interface User { id: string; name: string; email: string; role: string; }

// Update form — all fields optional:
type UserUpdateProps = Partial<Omit<User, 'id'>>;

function UserUpdateForm(props: UserUpdateProps) {
  // name, email, role are all optional
}

Record with Mapped Types

Create lookup types where keys come from a union and values are a consistent shape.

type Status = 'idle' | 'loading' | 'success' | 'error';

type StatusConfig = Record<Status, {
  label: string;
  icon: React.ReactNode;
  color: string;
}>;

const statusConfig: StatusConfig = {
  idle: { label: 'Ready', icon: <ReadyIcon />, color: 'gray' },
  loading: { label: 'Loading...', icon: <Spinner />, color: 'blue' },
  success: { label: 'Done', icon: <CheckIcon />, color: 'green' },
  error: { label: 'Error', icon: <XIcon />, color: 'red' },
};

Picking Required Keys

Use conditional types with -? (remove optional) to extract only the required keys of a type.

type RequiredKeys<T> = {
  [K in keyof T]-?: undefined extends T[K] ? never : K;
}[keyof T];

interface FormData { name: string; email: string; phone?: string; }
type Required = RequiredKeys<FormData>; // 'name' | 'email'

Template Literal Types

Template literal types compose string literal types, enabling typed event names, CSS class strings, and API paths.

type EventName = 'click' | 'change' | 'focus';
type HandlerName = `on${Capitalize<EventName>}`;
// 'onClick' | 'onChange' | 'onFocus'

type ApiPath<R extends string> = `/api/${R}`;
type UserPath = ApiPath<'users'>; // '/api/users'

Extracting Props Conditionally

Use Extract and Exclude to filter union types.

type AllProps = 'onClick' | 'onHover' | 'onChange' | 'style';
type EventHandlers = Extract<AllProps, `on${string}`>;
// 'onClick' | 'onHover' | 'onChange'

type NonEventProps = Exclude<AllProps, `on${string}`>;
// 'style'

Mapped Types for Form Validation

Generate validation error types that mirror your form data shape — one error message string per field.

interface LoginForm { email: string; password: string; }

type FormErrors<T> = { [K in keyof T]?: string };
type LoginErrors = FormErrors<LoginForm>;
// { email?: string; password?: string }

const errors: LoginErrors = { email: 'Invalid email format' };

Discriminated Mapped Types

Combine mapped types with conditional types to create types that change shape based on a discriminant.

type EventMap = {
  click: { x: number; y: number };
  keydown: { key: string; code: string };
  resize: { width: number; height: number };
};

type Handler<E extends keyof EventMap> = (event: EventMap[E]) => void;

function on<E extends keyof EventMap>(event: E, handler: Handler<E>) {
  window.addEventListener(event, handler as EventListener);
}

When Not to Over-Engineer Types

Conditional and mapped types add power but also complexity. Use them when they eliminate real duplication or prevent actual bugs — not just to demonstrate TypeScript knowledge.

Quick Check

What does the mapped type { [K in keyof T]?: T[K] } do?

Recap

Conditional types (T extends U ? X : Y) create types that branch based on assignability. Mapped types ([K in keyof T]) transform each property of a type. Use them for update-form partial types, typed event maps, form error shapes, and template literal API paths.

Frequently asked questions

Is the “Conditional & Mapped Types in React” lesson free?

Yes — the full text of “Conditional & Mapped Types in React” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Conditional & Mapped Types in React”?

Build component prop types that change shape based on other prop values using conditional types. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Conditional & Mapped Types in React” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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