Overloading by Arity
You'll learn how to create function overloads that differ based on the number of parameters they accept.
What Is Arity?
Arity refers to the number of parameters a function accepts. A function with one parameter has an arity of 1, two parameters has an arity of 2, and so on. When you overload by arity, you're telling TypeScript "this function behaves differently depending on how many arguments you pass."
Why Overload by Arity?
Sometimes a function logically does different things based on whether you call it with one argument, two arguments, or more. Overloading by arity lets you:
- Provide different return types based on parameter count
- Make certain parameters required only when others are present
- Create more intuitive APIs that adapt to usage
Basic Example
// Overload signatures
function greet(name: string): string;
function greet(firstName: string, lastName: string): string;
// Implementation signature
function greet(firstName: string, lastName?: string): string {
if (lastName === undefined) {
return `Hello, ${firstName}!`;
}
return `Hello, ${firstName} ${lastName}!`;
}
const casual = greet("Alice"); // "Hello, Alice!"
const formal = greet("Alice", "Johnson"); // "Hello, Alice Johnson!"
The function behaves differently with one parameter versus two. TypeScript uses the overload signatures to type-check calls and determine return types, while the implementation handles the actual logic.
The Pattern
Think of overloading by arity like a restaurant menu with combo options: order one item, get a snack; order two items, get a meal. The kitchen (implementation) can handle both, but the menu (overload signatures) makes the options clear.
Key Takeaway: Overloading by arity lets you define type-safe functions that accept different numbers of parameters, with TypeScript enforcing which combinations are valid at compile time.