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>.
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);
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.
<T> appears only once in a function signature, you probably do not need a generic—use a concrete type or unknown.<string> on every call: Let TypeScript infer <T> from your arguments (firstItem(["a", "b"])) unless inference cannot determine it.extends constraints: Calling arg.length on an unconstrained <T> fails until you write <T extends { length: number }>.<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.
Yes. class CacheStore<T> { private items = new Map<string, T>(); ... } lets you build reusable typed containers.
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.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.