Function Overloads
What
Function overloads allow a single function to be called in multiple distinct ways by providing multiple signatures (overloads) for the same implementation.
How
You declare the public signatures before the actual function implementation. The implementation signature must be compatible with all overloads:
// Overload signatures
function format(data: string): string;
function format(data: number, base: number): string;
// Implementation signature
function format(data: any, base?: number): string {
if (typeof data === "number") {
return data.toString(base);
}
return data.trim();
}
Why
Overloads are essential for constraining a function’s behavior when certain parameters are interdependent. For example, if passing a true boolean requires an additional Date object, overloads can enforce that specific combination, which is impossible with simple optional parameters.
Summary
Use overloads to provide a clean, type-safe API for functions that have complex or flexible argument requirements.