Mastering TypeScript Generics
A deep dive into TypeScript generics — from basic type parameters to advanced conditional types and mapped types that make your code truly reusable.
Why Generics Change Everything
TypeScript without generics is like a library with only one book. Generics let you write functions and classes that work with any type while still maintaining full type safety.
The Basic Pattern
function identity<T>(value: T): T {
return value;
}
const num = identity<number>(42); // type: number
const str = identity<string>("hello"); // type: string
Generic Constraints
Use extends to constrain what types are allowed:
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(value: T): T {
console.log(value.length);
return value;
}
logLength("hello"); // ✓
logLength([1, 2, 3]); // ✓
logLength(42); // ✗ Error: number has no length
Conditional Types
type IsArray<T> = T extends any[] ? true : false;
type A = IsArray<string[]>; // true
type B = IsArray<string>; // false
Mapped Types
type Readonly<T> = {
readonly [K in keyof T]: T[K];
};
type Optional<T> = {
[K in keyof T]?: T[K];
};
Practical Patterns
- Use
keyof Tto iterate over object keys safely - Use
inferinside conditional types to extract nested types - Combine generics with utility types like
Partial,Required,Pick,Omit
Generics are the foundation of every great TypeScript library. Master them and your code becomes infinitely more expressive.
Written by
Soren Lindqvist
Engineer. Ships the TypeScript, Docker, and database pieces, usually after breaking them in production first.
Related Articles
How to Contribute to Open Source
Your first open source contribution doesn't have to be a major feature. A practical guide to finding projects, making meaningful contributions, and building your reputation.
State Management in 2024: What Actually Works
Redux is no longer the default answer. Compare Zustand, Jotai, TanStack Query, and React's built-in tools to find the right solution for your app.
Advanced Tailwind CSS Patterns
Go beyond utility classes. Learn Tailwind's plugin system, custom design tokens, component extraction, and the patterns that scale to large codebases.