16. Advanced Generics & Conditional Types
TypeScript Metaprogramming
Welcome to Advanced TypeScript. Here, we stop writing static types manually, and start writing logic that generates types dynamically. This is the realm of library authors (like the creators of React or Zustand) who need to provide perfect autocomplete for highly flexible code.
Advanced Generics: API Wrappers
Generics are powerful when wrapping API responses. An API usually has a standard envelope (data, error, status), but the actual payload changes depending on the endpoint.
Generic Constraints (`extends`)
Sometimes you want a function to be generic, but you need to guarantee that the passed type has at least some specific properties. You "constrain" the generic using the extends keyword.
Conditional Types
You can write logic in your types using a syntax identical to the JavaScript ternary operator. This allows a type to change its shape based on a condition.
Knowledge Check
Ready to test your understanding of 16. Advanced Generics & Conditional Types?