Course contentsShow
← TypeScript
Lesson 276 of 1,7966. FunctionsFree lesson

Common Pitfalls with Overloads

Avoiding order mistakes and overly broad implementation signatures.

Common Pitfalls with Overloads

You'll learn how to avoid two critical mistakes: placing overloads in the wrong order and making your implementation signature too permissive.

The Two Most Common Overload Mistakes

When writing function overloads, beginners often stumble in two areas that can break type safety or cause confusing errors.

Pitfall 1: Order Matters — Specific Before General

TypeScript checks overload signatures from top to bottom and uses the first match. If you place a general overload before a specific one, the specific case will never be reached.

// ❌ WRONG: General overload comes first
function format(value: any): string;
function format(value: number): string;
function format(value: string): string;
function format(value: any): string {
  return String(value);
}

// The number overload is never used! 'any' catches everything first.

The fix: Always order from most specific to most general:

// ✅ CORRECT: Specific overloads first
function format(value: number): string;
function format(value: string): string;
function format(value: boolean): string;
function format(value: number | string | boolean): string {
  return String(value);
}

Pitfall 2: Implementation Signature Too Broad

If your implementation signature is visible or broader than necessary, it can accept values that none of your overloads actually support:

// ❌ WRONG: Implementation signature is too permissive
function process(x: number): number;
function process(x: string): string;
function process(x: any): any {  // 'any' is too broad
  return x;
}

// Inside the function, you lose type safety

The fix: Make your implementation signature precisely match the union of all overload cases, and remember it's not callable from outside.

Key Takeaway: Place specific overloads before general ones, and keep your implementation signature as narrow as possible while still covering all overload cases.