Understanding TypeScript Generics
2026-04-15Programming
A deep dive into how generics work in TypeScript and why they make your code safer and more reusable.
Why generics matter
Generics let you write functions and data structures that work across many types while preserving type safety. Without them, you'd have to choose between any (unsafe) or writing the same function many times for each type.
A simple example
// Without generics
function firstItem(arr: number[]): number {
return arr[0]
}
// With generics
function firstItem<T>(arr: T[]): T {
return arr[0]
}
// Works for any type
firstItem([1, 2, 3]) // number
firstItem(['a', 'b', 'c']) // string
Constraints
You can constrain what types a generic accepts using extends:
function getLength<T extends { length: number }>(value: T): number {
return value.length
}
getLength('hello') // 5
getLength([1, 2, 3]) // 3
Practical use: type-safe fetching
async function fetchJson<T>(url: string): Promise<T> {
const res = await fetch(url)
return res.json() as T
}
const user = await fetchJson<{ name: string; age: number }>('/api/user')
Further reading
- TypeScript Handbook: Generics — the official docs are actually great here
- Matt Pocock's Total TypeScript course