Overloads vs Union Parameters
What you'll learn: How to decide between function overloads and union parameter types for handling multiple function signatures.
Two Approaches to Variation
You've learned both function overloads and union parameter types. Now comes a critical question: when should you use each?
Both techniques let a function accept different input types, but they solve different problems:
Union parameters are simpler—they say "this parameter can be type A OR type B." You write one function signature with union types in the parameters and/or return type.
Overloads are more precise—they let you express relationships between specific input types and their corresponding output types. Each overload signature declares a distinct contract.
When Unions Fall Short
Consider a format function: when you pass a number, you get a string; when you pass a Date, you also get a string. A union works great here:
function format(value: number | Date): string {
return value.toString();
}
But what if the return type depends on the input type? Say process returns number for number input, and string for string input. A union falls apart:
// Misleading—suggests ANY combination is possible
function process(input: number | string): number | string {
return typeof input === 'number' ? input * 2 : input.toUpperCase();
}
const result = process(5); // Type: number | string (too loose!)
When Overloads Shine
Overloads capture the precise input-output relationship:
function process(input: number): number;
function process(input: string): string;
function process(input: number | string): number | string {
return typeof input === 'number' ? input * 2 : input.toUpperCase();
}
const result = process(5); // Type: number (precise!)
Key Takeaway: Use union parameters when inputs can vary but outputs don't depend on specific input types; use overloads when you need to preserve the relationship between specific parameter types and their corresponding return types.