TypeScript Generics Explained: From Basics to Constraints and Inference
Understand TypeScript generics: generic functions and types, constraints with extends, default type parameters, inference, keyof patterns and common mistakes...
Published December 6, 2026
Generics let you write functions, classes and types that work with many types while keeping full type safety. Instead of using any and losing information, a generic captures the actual type a caller uses and carries it through. They are the foundation of nearly every well-typed library, from React hooks to API clients.
The concept
A generic function declares a type parameter in angle brackets: function first<T>(items: T[]): T | undefined. When called with an array of strings, TypeScript infers T as string and the return type becomes string | undefined. The same function works for numbers or users without any casts.
Constraints restrict what a type parameter may be, using extends: <T extends { id: string }> guarantees an id property. Combined with keyof and indexed access types, constraints enable precise helpers like getProperty<T, K extends keyof T>(obj: T, key: K): T[K]. Default type parameters (<T = unknown>) and inference from arguments keep call sites clean.
How inference works
Common patterns
| Pattern | Example | Use |
|---|---|---|
| Generic function | function wrap<T>(v: T): { value: T } | Preserve input type |
| Constraint | <T extends { id: string }> | Require shape |
| keyof constraint | <T, K extends keyof T>(o: T, k: K): T[K] | Type-safe property access |
| Default parameter | type ApiResponse<T = unknown> | Sensible fallback |
| Generic interface | interface Repo<T> { find(id: string): Promise<T> } | Reusable contracts |
any vs generics
| Instead of | Use |
|---|---|
| function first(items: any[]): any | function first<T>(items: T[]): T | undefined |
| Casting results: data as User | fetchJson<User>(url) with runtime validation |
| Overloads for each type | One generic with constraints |
Practical examples
Type-safe property getter
keyof and indexed access types together.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key]
}
const user = { id: 'u1', age: 31 }
const age = getProperty(user, 'age') // number
// getProperty(user, 'email') // error: '"email"' is not assignable to '"id" | "age"'Generic API client with validation
Generics describe the shape; zod checks it at runtime.
import { z } from 'zod'
async function fetchJson<T>(url: string, schema: z.ZodType<T>): Promise<T> {
const res = await fetch(url)
return schema.parse(await res.json())
}
const User = z.object({ id: z.string(), name: z.string() })
const user = await fetchJson('/api/me', User) // inferred as { id: string; name: string }Constrained generic for entities
Require an id while keeping the full type.
function indexById<T extends { id: string }>(items: T[]): Record<string, T> {
return Object.fromEntries(items.map(i => [i.id, i]))
}Common mistakes
- Using any instead of a type parameter.
- Adding type parameters that appear only once (they add nothing).
- Over-constraining generics so they no longer fit real use.
- Treating generic type arguments as runtime validation.
Key takeaways
- Generics preserve type information across functions and types.
- Constraints (extends) require shapes; keyof enables precise access.
- Let inference work; annotate only when needed.
- Pair generics with runtime validation at system boundaries.
FAQ
When should I use a generic?
When a type parameter links inputs to outputs or relates several parameters. If it appears only once, you probably do not need it.
What is the difference between T extends X and T = X?
extends is a constraint (T must be assignable to X); = sets a default when no type is supplied or inferred.
Can generics have multiple parameters?
Yes, like Map<K, V> or function pick<T, K extends keyof T>(...).