Lesson

TypeScript Generics

10 min reading
Free Course

TypeScript Generics: Reusable Components Without Losing Types

TypeScript generics let functions, interfaces, and classes work across many types while preserving exact type relationships between inputs and outputs. Instead of falling back to any, a type parameter like <T> acts as a placeholder filled automatically when the function is called.

You already use generics daily whenever you write Array<string> or Promise<User>.

Generic Functions and Constraints (extends)

Add extends on a type parameter to require certain fields while keeping the rest of the caller's exact object type intact.

interface ApiResponse<T> {
  ok: boolean;
  data: T;
}

function firstItem<T>(items: readonly T[]): T | undefined {
  return items[0];
}

function getById<T extends { id: number }>(list: readonly T[], targetId: number): T | undefined {
  return list.find((item) => item.id === targetId);
}

const users = [{ id: 1, name: "Tariq" }, { id: 2, name: "Lina" }];
const found = getById(users, 2); // Inferred as { id: number; name: string } | undefined
const wrapped: ApiResponse<number> = { ok: true, data: firstItem([10, 20]) ?? 0 };
console.log(found?.name, wrapped.data);

Default Generic Parameters and Multiple Type Params

Just like default function values, you can assign a default type: interface PageResult<T = unknown> { items: T[]; total: number; }. You can also declare multiple type parameters together, such as <TKey, TValue>, whenever a helper maps keys to values across a collection.

Common Mistakes to Avoid

  • Adding unnecessary generic type parameters: If <T> appears only once in a function signature, you probably do not need a generic—use a concrete type or unknown.
  • Manually passing <string> on every call: Let TypeScript infer <T> from your arguments (firstItem(["a", "b"])) unless inference cannot determine it.
  • Forgetting extends constraints: Calling arg.length on an unconstrained <T> fails until you write <T extends { length: number }>.

Frequently Asked Questions

What does <T, K extends keyof T> mean?

It defines T as an object type and restricts K to only valid property key names of T, enabling type-safe property readers.

Can classes also be generic?

Yes. class CacheStore<T> { private items = new Map<string, T>(); ... } lets you build reusable typed containers.

Why do standard libraries name generics T, K, and V?

T stands for Type, K for Key, V for Value, and E for Element—though descriptive names like TItem or TPayload are clearer in complex signatures.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum