Overload Resolution Order Matters
You'll learn: Why the ordering of your function overload signatures is critical and how TypeScript matches them from top to bottom.
When you define function overloads, TypeScript doesn't magically pick the "best" match—it checks your overload signatures in order from top to bottom and uses the first one that matches. This means if you put a general overload before a specific one, the specific overload will never be reached.
The Top-to-Bottom Matching Rule
Think of overload signatures like a series of airport security checkpoints. TypeScript walks through each checkpoint (signature) in order, and as soon as your arguments pass one checkpoint, that's the route you're taking—no looking ahead for a "better" match.
// ❌ Wrong: General before specific
function format(value: string | number): string;
function format(value: number, decimals: number): string;
function format(value: string | number, decimals?: number): string {
// implementation
}
format(42, 2); // Type error! First overload matches, second never reached
The first overload accepts string | number with one parameter. When you call format(42, 2), TypeScript sees that 42 matches the first signature... but that signature only allows one argument. Type error! The second, more specific overload is never considered.
// ✅ Correct: Specific before general
function format(value: number, decimals: number): string;
function format(value: string | number): string;
function format(value: string | number, decimals?: number): string {
if (typeof value === "number" && decimals !== undefined) {
return value.toFixed(decimals);
}
return String(value);
}
format(42, 2); // ✅ Matches first overload
format(42); // ✅ Matches second overload
format("hello"); // ✅ Matches second overload
Now the two-parameter number case is checked first, so it gets matched correctly.
Why This Matters
Incorrect ordering silently breaks type safety. Your implementation might work perfectly at runtime, but callers get misleading type errors or incorrect autocomplete because TypeScript matched the wrong signature.
Key Takeaway: Always order overload signatures from most specific to most general—TypeScript matches top-to-bottom and stops at the first match.