ReviseAlgo Logo

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.

Last Updated: July 29, 2026 10 min read
Generics are a core feature of TypeScript that allow you to create reusable, type-safe components, functions, and data structures that work across a variety of types rather than a single fixed 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

ApproachReusable?Type-Safe?Inferred Return Type
Hardcoded TypesNoYesSpecific Hardcoded Type
Using anyYesNoany (Destroys static checking)
| Generics () | Yes | Yes | Exact Type Passed in (T) |