Skip to content
TypeScript Essentials

Lesson 5 of 6 · 20 min

x
5/6

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

Conditional & Mapped Types

Mapped types iterate over key unions to transform existing properties into new types using the in keyword ([K in keyof T]). You can modify property modifiers during mapping, adding or removing readonly and ? optional modifiers (e.g., -readonly [K in keyof T]-?: T[K]).

Conditional types choose between two potential types based on a type relationship test (T extends U ? X : Y). Combined with the infer keyword, conditional types can extract inner types from generic wrappers, such as unwrapping a Promise (type Unpack<T> = T extends Promise<infer U> ? U : T).

Before
Manual Getter Method Interface
1interface Person {2  name: string;3  age: number;4}5// Manual repetition of getter methods6interface PersonGetters {7  getName: () => string;8  getAge: () => number;9}
After
Mapped Type for Dynamic Method Generation
1type CreateGetters<T> = {2  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];3};4 5interface Person {6  name: string;7  age: number;8}9 10type PersonGetters = CreateGetters<Person>;11// Result: { getName: () => string; getAge: () => number; }

Exercise

Write a mapped type Nullable<T> that converts all properties of T to accept T[K] | null.

Check your understanding

  • What does keyof T produce in TypeScript?Show answer

    Answer

    A union of string, number, or symbol property names of type T.
  • What does the infer keyword do in conditional types?Show answer

    Answer

    It introduces a temporary type variable inside the extends clause to be extracted and returned.
Previous

Progress is saved in this browser.

Next Lesson