Generics Purpose
Question
Why use generics in TypeScript?
Hint
Generics preserve type information through function calls.
Explanation
Generics allow writing reusable code that works with multiple types while preserving type safety. Example: function identity<T>(x: T): T { return x; }. The type parameter T is inferred from the argument or explicitly specified: identity<string>("hi"). Generics are used for collections (Array<T>), utility functions (map, filter), and data structures. Constraints (T extends SomeType) limit what types are allowed. Generics are compile-time only — they are erased in the output JavaScript.
Related Resources
Related Lessons
- Generics
Learn generics.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.