Generics
Introduction to Generics — Why?
Understand the fundamental purpose of Generics in TypeScript, type variables (<T>), reusable type abstraction, and moving beyond the unsafe 'any' type.
Generics provide a way to tell TypeScript: "I want to capture the specific type passed in by the caller and use that exact type for parameters, returns, or properties later."
1. The Problem: Duplication vs Loss of Type Safety
Imagine writing an identity function that returns whatever value is passed to it:
Approach 1: Hardcoding Specific Types (Code Duplication)
Approach 2: Using any (Loss of Type Safety)
2. The Solution: Generics ()
Generics use a Type Variable (conventionally ) to capture the type provided by the caller:
3. Benefits of Generics
1. Reusability: Write a data structure or utility function once and use it safely with numbers, strings, or custom domain interfaces.
2. Type Preservation: Avoids falling back to any. The exact input type is preserved throughout function execution.
3. Compiler Verification: Prevents passing incompatible arguments to generic containers.
4. Interactive Code Playground
Test generic identity and container functions below:
5. Summary Table
| Approach | Reusable? | Type-Safe? | Inferred Return Type |
|---|---|---|---|
| Hardcoded Types | No | Yes | Specific Hardcoded Type |
Using any | Yes | No | any (Destroys static checking) |
) | Yes | Yes | Exact Type Passed in (T) |