keyof, Mapped and Conditional Types
These features let library authors - and you - describe very precise types: "a function that returns the type of whichever property you ask for", or "the same object but every field is a boolean". You'll read them often in library code even if you rarely write them.
keyof and indexed access
Example
Mapped types
A mapped type loops over keys to build a new type. This is how Partial and Readonly are made:
Example
Conditional types
Example
Template literal types
Example
You won't write conditional types every day. But knowing them helps you read library types and error messages.
Key points
- keyof and indexed access read types from types.
- Mapped types build new types from keys.
- Conditional types and infer choose types by rules.
📝 Test yourself
1. What is keyof Product?
2. What does { [K in keyof T]: boolean } build?
3. Fill in the keyword that captures a type inside a conditional type:
type ItemOf<T> = T extends ( U)[] ? U : never;
