Constraining One Type Parameter to Another
What you'll learn: How to use extends to require that one generic type parameter must be compatible with another type parameter in the same function or class signature.
Sometimes you need multiple type parameters in a generic function, but they're not independent — one must be related to the other. TypeScript lets you express this relationship using extends to constrain one type parameter based on another.
The Core Idea
You can write a constraint like <T, U extends T>, which means "accept two type parameters, but U must be a subtype of (assignable to) T." This creates a hierarchy between your type parameters.
Why this matters: It prevents callers from passing completely unrelated types when the logic requires them to be compatible.
Basic Syntax
function copyProperties<T, U extends T>(target: T, source: U): T {
return { ...target, ...source };
}
const base = { name: "Alice" };
const extra = { name: "Bob", age: 30 };
// ✅ Works: extra has all properties of base (and more)
copyProperties(base, extra);
// ❌ Error: number is not assignable to { name: string }
// copyProperties(base, 42);
Here, U extends T means source must have at least the same shape as target.
Another Example
function merge<T, U extends T>(obj1: T, obj2: U): U {
return { ...obj1, ...obj2 };
}
The constraint ensures obj2 is compatible with obj1 before merging.
Key Takeaway: Use <T, U extends T> to require one type parameter to be a subtype of another, ensuring related generics maintain type compatibility within the same signature.