What Are Generics in TypeScript?

What Are Generics in TypeScript?

Generics in TypeScript are a way to create reusable, flexible, and type-safe code components—like functions, interfaces, or classes—that can work with different types without losing the benefits of type checking.

Instead of hardcoding a type, you use a type variable that gets replaced with a specific type when the code is used.


📦 Why Use Generics?

Without generics, you might write:

❌ Problem: You lose type safety. The return type is always any.

✅ With generics:

You get:

  • Type inference

  • Auto-completion

  • Compile-time safety


🧪 Generic Syntax Basics

  • T is a generic type parameter

  • It can be any valid identifier (like T, U, K, V)

  • You can have multiple type parameters


🧰 Generics in Different Contexts

✅ 1. Functions


✅ 2. Interfaces


✅ 3. Classes


✅ 4. Constraints with extends

You can limit what types are allowed:


✅ 5. Default Generic Types


✅ 6. Using keyof with Generics


🎯 When to Use Generics

Use generics when:

  • You want to write type-safe, reusable code

  • Your function/component works with multiple types

  • You want to retain type information across inputs and outputs


🚫 When Not to Use Generics

Avoid generics when:

  • The type is known and fixed

  • The logic is too specific to a single type

  • It adds unnecessary complexity

To view or add a comment, sign in

Others also viewed

Explore topics