Overloads vs Generic Union Parameters
You'll learn: How function overloads create multiple type signatures that resolve separately, while generic union parameters create a single signature that branches internally—and when to choose each approach.
The Core Distinction
When you need a function to handle multiple types differently, you have two main tools:
Function overloads define separate type signatures that TypeScript checks sequentially. Each overload is like a distinct contract, and TypeScript picks the first matching one.
Generic union parameters use a single signature with a type parameter constrained to a union. TypeScript distributes the union through the logic, creating branches internally.
Think of overloads like multiple specialized checkout lanes at a store (express, returns, regular), while generic unions are like a single smart lane that adapts based on what you bring.
The Functional Difference
With overloads, you write distinct signatures for each case:
function process(input: string): string[];
function process(input: number): number[];
function process(input: string | number): string[] | number[] {
// Implementation must handle both
if (typeof input === 'string') {
return input.split(',');
}
return [input];
}
const a = process("hello"); // Type: string[]
const b = process(42); // Type: number[]
With generic union parameters, you use one signature that branches:
function process<T extends string | number>(
input: T
): T extends string ? string[] : number[] {
if (typeof input === 'string') {
return input.split(',') as any;
}
return [input] as any;
}
const a = process("hello"); // Type: string[]
const b = process(42); // Type: number[]
When to Use Each
Use overloads when:
- You have fundamentally different parameter patterns (different arity, different parameter types)
- The type relationships are simple and direct
- You want clearer, more readable signatures
Use generic unions when:
- You need to preserve the exact input type in the output
- You're building type transformations
- The same logic applies regardless of type, but output types differ
Key Takeaway: Overloads create separate type signatures that TypeScript resolves one-by-one, while generic union parameters create one signature that internally distributes across union members—choose overloads for clarity with distinct cases, generics for type preservation and transformation.