TypeScript · Frontend · Backend · JavaScript
TypeScript Generics: A Practical Guide with Real-World Examples
Learn TypeScript generics through real scenarios: a typed API client, constraints with extends, keyof, conditional types, default type parameters and avoiding over-engineering.

Generics look like one of TypeScript's scariest features at first, yet they save the most time in daily work. Instead of academic Box<T> examples, this guide uses the kind of code I actually write in Angular and Node.js projects.
The problem: repeated code with different types
async function getDevice(id: string): Promise<Device> { /* ... */ }
async function getRun(id: string): Promise<Run> { /* ... */ }
async function getUser(id: string): Promise<User> { /* ... */ }
Same logic, different return types. A generic function puts it in one place:
async function getJson<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json() as Promise<T>;
}
const device = await getJson<Device>('/api/devices/42');
T is a type parameter decided at the call site.
Careful:
as Promise<T>is a promise to the compiler, not a runtime check. Validate external data with a schema such as Zod; I cover that in error handling in TypeScript Node.js APIs.
Constraints: extends
Sometimes T must have a certain shape:
interface Entity { id: string; updatedAt: string; }
function newest<T extends Entity>(items: T[]): T | undefined {
return [...items].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0];
}
newest works with any entity but guarantees id and updatedAt exist. And it returns exactly the type you passed (Device, Run...), not just Entity.
Safe property access with keyof
function sortBy<T, K extends keyof T>(items: T[], key: K): T[] {
return [...items].sort((a, b) => (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0));
}
sortBy(devices, 'name'); // fine
sortBy(devices, 'nmae'); // compile error
Typos are caught at compile time, and the IDE autocompletes property names.
A typed contract map
In realtime systems it pays to define event names and payloads in one map:
interface Events {
'device.status': { deviceId: string; status: 'online' | 'offline' };
'run.finished': { runId: string; passed: boolean };
}
function on<E extends keyof Events>(event: E, handler: (payload: Events[E]) => void) { /* ... */ }
on('run.finished', (payload) => payload.passed); // payload is typed automatically
This is the generic version of the typed message contract from realtime systems with Node.js and WebSocket.
Conditional and utility types
TypeScript's built-in utility types are written with generics too: Partial<T>, Pick<T, K>, Omit<T, K>, Record<K, V>, ReturnType<F>. You can write your own conditional types:
type ApiResult<T> = T extends void ? { ok: true } : { ok: true; data: T };
But be careful: three levels of nested conditional types become code half the team can't read.
Default type parameters
interface Page<T, C = string> { data: T[]; next: C | null; }
const page: Page<Run> = { data: [], next: null };
When not to write a generic
- When it serves a single type: write it concretely first and generalise when the second use arrives.
- When the type parameter appears only once (
function log<T>(x: T): void), the generic is pointless;unknownis enough. - When error messages become unreadable: simplify the types.
Conclusion
Generics keep type safety without repeating code. Typed clients, extends constraints, keyof for property safety and event maps cover most daily needs. The rule: readability comes before type cleverness.


