TypeScript generics allow you to create components and functions that work with a variety of types while maintaining full type safety. Once you understand them, you'll wonder how you ever coded without them.
What Are Generics?
Generics are type-level parameters. Just as a function can take a runtime value as a parameter, a generic can take a type as a parameter. The result is a single definition that works correctly for any type you pass in.
Constraints and Defaults
Use the extends keyword to constrain what types can be passed to a generic. This gives you access to specific properties while keeping the function reusable. Combine with default type parameters to make complex APIs ergonomic for common cases.
Real-World Patterns
Generic hooks, generic API response wrappers, and generic form handlers are the patterns I reach for most. They eliminate entire classes of bugs by making the type flow from the call site down through the entire function body.