3 Things I Wish I Knew Earlier About TypeScript Generics

When working on a large-scale B2B application, you might encounter complex type definitions.
Taking the time to understand the advanced concepts of TypeScript Generics can significantly enhance your comprehension and help you manage these complexities more effectively.
Infer: Extract Types
The infer
keyword is used within conditional types to extract type information from other types:
In this example, we extracted the User
type from the UserApiResponse
.
Mapped Types: Creating New Types
Mapped types allow you to create new types based on existing ones by transforming their properties.
Here’s a simple example of creating a read-only type:
A more complex example that annotates a type with typical form fields:
keyof: Generic Constraints
The keyof
keyword allows you to create more specific and powerful generic types by restricting the types that can be used with a generic.
Here’s a useful function to transform properties of an object:
Another advanced use case is building a query builder:
Learn more: