17. Mapped Types & Deep Utility Types
Generating Types from Types
In the previous module, we learned Conditional Types. Now, we introduce Mapped Types. Mapped Types allow you to loop over the keys of one object to automatically generate a completely new object type. This is exactly how utility types like Partial and Readonly are built internally by TypeScript.
The `keyof` Operator
Before mapping, you must understand keyof. It extracts all the property names of an interface and returns them as a literal Union Type.
Mapped Types
A Mapped Type uses the syntax [K in keyof T] to loop through properties.
Utility Types Deep Dive: ReturnType
TypeScript can extract the type data out of JavaScript functions you have already written. ReturnType<T> looks at a function and extracts the exact shape of the object it returns.
Utility Types Deep Dive: Parameters
Similarly, Parameters<T> extracts the arguments a function expects and returns them as a Tuple.
Required <T>
We've seen Partial (makes everything optional). Required is the opposite. It strips away all optional ? modifiers, forcing every property to be provided.
Knowledge Check
Ready to test your understanding of 17. Mapped Types & Deep Utility Types?