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).
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 answerHide answer
Answer
A union of string, number, or symbol property names of type T.What does the infer keyword do in conditional types?Show answerHide answer
Answer
It introduces a temporary type variable inside the extends clause to be extracted and returned.