Generics · Lesson 11 of 17
TypeScript Generics Explained
Suppose you write first(items) that returns the first element of an array. With any you lose the type; with a separate version per type you repeat yourself. Generics let a function, interface or class work with any type while keeping that type: first([1, 2]) returns a number, first(["a"]) a string. Every serious TypeScript library – React's useState, Array<T>, Promise<T> – is built on them.
In this lesson
- Why generics beat
any - Generic functions and inference
- Generic interfaces and type aliases
- Generic classes and default type parameters
The problem with any
function firstAny(items: any[]): any {
return items[0];
}
const n = firstAny([10, 20]); // type: any – the information is lost
console.log(n.toUpperCase()); // compiles, then crashes at run time
TypeError: n.toUpperCase is not a function
Generic functions
function first<T>(items: readonly T[]): T | undefined { // T is a type parameter
return items[0];
}
function pair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}
const num = first([10, 20, 30]); // T inferred as number → number | undefined
const word = first(["ts", "js"]); // T = string
const p = pair("Asha", 91); // [string, number]
const explicit = first<boolean>([true]); // T written explicitly
console.log(num?.toFixed(1), word?.toUpperCase(), p, explicit);
10.0 TS [ 'Asha', 91 ] true
What happens at first([10, 20, 30])
- Infer Tthe argument is number[], so T = number
- Substitutethe signature becomes (items: readonly number[]) => number | undefined
- Checkevery use of the result is checked as a number
- Erasethe emitted JavaScript has no T at all – zero runtime cost
Generic interfaces and type aliases
interface ApiResponse<T> {
status: number;
data: T;
error?: string;
}
type Paginated<T> = {
items: T[];
page: number;
total: number;
};
interface Course { slug: string; title: string }
const one: ApiResponse<Course> = { status: 200, data: { slug: "ts", title: "TypeScript" } };
const list: ApiResponse<Paginated<Course>> = {
status: 200,
data: { items: [{ slug: "sql", title: "SQL" }, { slug: "cpp", title: "C++" }], page: 1, total: 2 },
};
console.log(one.data.title, "|", list.data.items.map((c) => c.title).join(", "), list.data.total);
TypeScript | SQL, C++ 2
One generic response type describes every endpoint. This is exactly how typed API clients and React Query hooks expose your data.
Generic classes
class TypedCache<K, V> {
private store = new Map<K, { value: V; expires: number }>();
constructor(private ttlMs: number) {}
set(key: K, value: V, now: number): void {
this.store.set(key, { value, expires: now + this.ttlMs });
}
get(key: K, now: number): V | undefined {
const entry = this.store.get(key);
if (!entry || entry.expires <= now) {
this.store.delete(key);
return undefined;
}
return entry.value;
}
}
const prices = new TypedCache<string, number>(1000); // string keys, number values
prices.set("pen", 20, 0);
console.log(prices.get("pen", 500), prices.get("pen", 1500), prices.get("bag", 0));
// prices.set("book", "450", 0); // error: string is not assignable to number
20 undefined undefined
Default type parameters
interface Event<Payload = undefined> {
name: string;
payload: Payload;
}
const ping: Event = { name: "ping", payload: undefined }; // Payload = undefined
const login: Event<{ userId: number }> = { name: "login", payload: { userId: 7 } };
console.log(ping.name, login.name, login.payload.userId);
ping login 7
Naming and when to use generics
- Use a generic when the same type appears in two places (input and output, key and value) and must stay connected.
- Single letters (
T,K,V) are conventional for simple cases; descriptive names (TItem,TResponse) help in complex ones. - If a type parameter is used only once, you probably don't need it – use the concrete type or
unknown.
Practice
Try it yourself
Write a generic
groupBy<T>(items: T[], key: (item: T) => string): Record<string, T[]>.Show solution
function groupBy<T>(items: readonly T[], key: (item: T) => string): Record<string, T[]> { const groups: Record<string, T[]> = {}; for (const item of items) (groups[key(item)] ??= []).push(item); return groups; } const orders = [{ id: 1, city: "Pune" }, { id: 2, city: "Delhi" }, { id: 3, city: "Pune" }]; const byCity = groupBy(orders, (o) => o.city); console.log(Object.keys(byCity), byCity["Pune"]?.map((o) => o.id));[ 'Pune', 'Delhi' ] [ 1, 3 ]
Quick check
Why use a generic instead of any?
Generics keep the type connected between input and output; any throws it away.
Do generics exist in the emitted JavaScript?
No – they're erased like all types.
What does interface Box<T = string> mean?
T defaults to string when no type argument is given.
Summary
- Generics are type parameters: reusable code that keeps precise types.
- TypeScript usually infers them from arguments; you can also write them explicitly.
- Generic interfaces, aliases and classes model containers, API responses and caches; defaults simplify common cases.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.