Constraint Solving and Unification
You'll learn: How TypeScript's compiler determines concrete types for generic type parameters by analyzing usage patterns and constraints.
The Core Idea
When you call a generic function without explicitly specifying type arguments, TypeScript doesn't guess randomly—it solves a system of constraints. Constraint solving is the algorithmic process where TypeScript examines all the contexts where a type parameter appears, collects requirements (constraints), and finds a type that satisfies all of them simultaneously. Unification is the mechanism for making two types "match" by finding substitutions for type parameters.
Think of it like solving algebraic equations: if you see x + 5 = 10, you solve for x. Similarly, if TypeScript sees identity<T>(42) where identity<T>(value: T): T, it needs to solve for T by unifying the parameter type T with the argument type 42 (or more precisely, number after widening).
How It Works
When you write code like:
function pair<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
const result = pair("hello", 42);
TypeScript performs constraint solving:
- Gather constraints:
Tmust match the type of"hello",Umust match the type of42 - Unify types: Find that
T = string(widened from literal"hello") andU = number - Validate: Check that these solutions satisfy all constraints
- Substitute: Replace
TwithstringandUwithnumberthroughout
The unification algorithm tries to find the most specific type that works. If you constrained T extends object, TypeScript would verify the solution satisfies this before accepting it.
Multiple Constraints
When multiple usage sites exist, TypeScript finds the best common type:
function pickFirst<T>(a: T, b: T): T {
return a;
}
const value = pickFirst(10, 20); // T = number (both are number)
const mixed = pickFirst("a", 42); // Error: can't unify string and number as T
Both parameters must be the same type T, so TypeScript must unify them. When unification fails, you get an error.
Key Takeaway: TypeScript's constraint solver examines every usage of a type parameter, builds a system of requirements, and uses unification to find type substitutions that satisfy all constraints—this is how generic type inference "just works" without explicit type arguments.