TypeScript Generics: A Practical Guide for Real Codebases
By Rishtaara Editorial Team9 min read
#TypeScript#Generics#Programming#Web Dev
Learn generics with constraints, keyof patterns, and when not to over-abstract — with examples you can drop into APIs and utilities.
01Why generics exist
Generics let you write functions and data structures that work across types while preserving type information. Without them, you reach for any and lose autocomplete and safety.
Think of a generic as a placeholder type parameter — like T — that the caller fills in.
Identity with a type parameter
function identity<T>(value: T): T {
return value;
}
const n = identity(42); // number
const s = identity("hi"); // string02Constraints and keyof
Often you need T to have certain fields. Use extends to constrain it. keyof helps you accept only real property names.
Constrained generic
function pluck<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}03Practical patterns
- API client methods that return typed JSON
- React component props with polymorphic as
- Result types like Result<T, E> for errors
- Repository interfaces Repository<T extends { id: string }>
04Common mistakes
- Over-abstracting before you have two real use cases
- Using any to silence errors instead of modeling data
- Forgetting to export generic types used in public APIs
Key takeaways
- Generics preserve types across reusable functions.
- Constrain with extends; index with keyof carefully.
- Add generics when reuse appears — not by default.
- Prefer precise models over any.
Frequently asked questions
When should I use unknown vs a generic?+
unknown is for values you must narrow. Generics are for preserving a caller-specified type through a function.
Are generics slow at runtime?+
They erase at compile time. Runtime cost is zero beyond the code you wrote.