Mutual Constraints Between Type Parameters
What you'll learn: How to create two-way relationships where type parameters enforce each other's allowed shapes.
Sometimes you need type parameters that reference each other in their constraints. This creates a bidirectional relationship where one generic constrains the other, and vice versa—like two gears that must fit together.
The Core Idea
You've already seen T extends K, but what about T extends SomeShape<U> and U extends OtherShape<T> in the same declaration? TypeScript allows type parameters to refer to each other in their constraint clauses, establishing mutual dependencies.
function pair<T extends { value: U }, U extends { ref: T }>(
a: T,
b: U
): [T, U] {
return [a, b];
}
// This enforces:
// - T must have a property 'value' of type U
// - U must have a property 'ref' of type T
When This Matters
Mutual constraints are powerful for modeling interconnected data structures—think nodes that reference each other, or API request/response pairs where each side knows about the other.
function linkPair<
A extends { partner: B },
B extends { partner: A }
>(first: A, second: B) {
return { first, second };
}
// Forces symmetrical relationships
This pattern appears in graph structures, state machines with transitions, and framework internals where types need to "shake hands."
The Circularity Trade-off
Be cautious: mutual constraints can create complex error messages and sometimes infinite type loops. Use them when the relationship is genuinely bidirectional, not just because you can.
Key Takeaway: Mutual constraints let two type parameters validate each other's shapes, creating type-safe bidirectional relationships for interconnected data.