Course contentsShow
← TypeScript
Lesson 1407 of 1,79632. Advanced PatternsFree lesson

Overloads for Related but Distinct Behaviors

Modeling functions where parameter types dictate completely different return types, such as string input returning object.

Overloads for Related but Distinct Behaviors

What you'll learn: How to use function overloads when parameter types completely change the return type, creating type-safe functions with context-dependent behavior.


The Core Problem

Sometimes you need a single function that behaves differently based on input type—not just accepting multiple types, but returning fundamentally different types based on what comes in. Union parameters can't capture this relationship.

Consider a function that converts data: when you pass a string, you get back a parsed object; when you pass an object, you get back a serialized string. These are related operations (serialization), but the behaviors are distinct.

Why Union Parameters Fall Short

If you tried function convert(input: string | object): string | object, TypeScript can't know which return type corresponds to which input. You lose precision.

The Overload Solution

Function overloads let you declare multiple signatures that explicitly pair input types with their corresponding return types:

// Overload signatures
function convert(input: string): { parsed: boolean };
function convert(input: object): string;

// Implementation signature (must handle all cases)
function convert(input: string | object): { parsed: boolean } | string {
  if (typeof input === 'string') {
    return { parsed: true };
  }
  return JSON.stringify(input);
}

// TypeScript knows the exact return type for each call
const obj = convert("data");    // Type: { parsed: boolean }
const str = convert({ a: 1 });  // Type: string

The Pattern: Signature Pairs

Each overload signature pairs a specific parameter type with its unique return type. The implementation must be compatible with all overloads but isn't directly callable—callers only see the overload signatures.

Key Takeaway: Use function overloads when parameter types dictate completely different return types, creating type-safe functions where the compiler understands the relationship between inputs and outputs.