Advanced Generic Patterns
Master advanced generics: constraints, defaults, variadic tuples, and recursive types.
What you'll learn
- Generic constraints with extends and the keyof operator
- Default type parameters and multi-level generics
- Variadic tuple types for flexible function signatures
- Recursive types for tree and linked-list structures
Concept
Constraints and keyof
Generic constraints limit what a type parameter can be. <T extends string> requires T to be a string or subtype. The most powerful constraint uses keyof: <T, K extends keyof T> ensures K is a valid key of T. This lets you write functions like function get<T, K extends keyof T>(obj: T, key: K): T[K] that are fully type-safe — the return type matches the property type at the given key.
Default Type Parameters
Generic type parameters can have defaults: interface Box<T = string> { value: T; }. If you use Box without a type argument, T defaults to string. Defaults are useful when a type is usually a specific value but occasionally varies. They also appear in utility types: Partial<T> has no default, but Record<K, T> could default K to string.
Variadic and Recursive Types
Variadic tuple types let you spread generic tuples: type Push<T extends unknown[], V> = [...T, V] appends V to any tuple. This enables type-safe concat, push, and other array operations. Recursive types reference themselves: type Json = string | number | boolean | null | Json[] | { [key: string]: Json } describes arbitrary JSON. These advanced patterns power libraries like zod and tRPC that build complex types from simple primitives.
Example
// keyof constraint — K must be a key of T, return type is T[K].
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Alice", age: 30 };
const id = getProperty(user, "id"); // number
const name = getProperty(user, "name"); // string
// Default type parameter.
interface Response<T = string> {
data: T;
status: number;
}
const text: Response = { data: "hello", status: 200 };
const nums: Response<number[]> = { data: [1, 2, 3], status: 200 };
// Variadic tuple — append a type to a tuple.
type Push<T extends unknown[], V> = [...T, V];
type Pair = Push<[number, string], boolean>; // [number, string, boolean]
// Recursive type — describe arbitrary JSON.
type Json =
| string
| number
| boolean
| null
| Json[]
| { [key: string]: Json };
const data: Json = { name: "Alice", tags: ["a", "b"], meta: { active: true } };
console.log(id, name, text.data, nums.data, data);
Constraints (extends keyof T) ensure type-safe property access. Default type parameters provide fallbacks. Variadic tuples spread generic arrays. Recursive types reference themselves for tree-like structures.
Try it
- JSON to TypeScript
Recursive types like Json describe arbitrary nested JSON structures.
- JSON Validator
Validate complex nested data against recursive type shapes.
Common mistakes
The mistake
Overcomplicating types with deep recursive generics that are hard to debug
The fix
Keep generics as simple as possible. If a type produces confusing error messages, simplify it. Type-level complexity has a maintenance cost — only use advanced patterns when they provide clear value.
The mistake
Forgetting to constrain generics and getting 'Type any is not assignable' errors
The fix
Add constraints with extends. Without constraints, T is treated as unknown or any in many contexts, leading to type errors. Constrain T to the shape you need.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.