Constraint Gotchas and Edge Cases
You'll learn the common traps and subtle mistakes when working with generic constraints that can confuse even experienced developers.
The Core Idea
Generic constraints are powerful, but they come with surprising edge cases. You can accidentally over-constrain (making your generic too restrictive), under-constrain (allowing invalid types through), or run into ordering issues where TypeScript can't infer what you expect. Understanding these gotchas helps you write more flexible, correct generic code.
Common Pitfalls
Constraint Order Matters
When using multiple type parameters with constraints, the order matters. A later parameter can reference an earlier one, but not vice versa:
// ✅ Works: U references T
function pair<T, U extends T>(first: T, second: U) {
return [first, second];
}
// ❌ Fails: Can't reference U before it's declared
// function broken<T extends U, U>(first: T, second: U) {}
Over-Constraining Kills Inference
Adding too many constraints can prevent TypeScript from inferring types:
// Over-constrained: forces explicit type arguments
function process<T extends { id: number; name: string }>(item: T) {
return item.id;
}
// Better: only constrain what you actually need
function betterProcess<T extends { id: number }>(item: T) {
return item.id;
}
The narrower your constraint, the less TypeScript can infer automatically from your call sites.
Constraint Doesn't Narrow in Body
A common mistake: assuming constraints narrow types inside the function. They specify minimum requirements, not exact types.
Key Takeaway: Use the loosest constraint that ensures safety—avoid over-constraining, respect parameter order when chaining constraints, and remember that constraints set minimum requirements, not exact types.