Function Overloading
JavaScript allows you to dramatically change a single function's exact behavior based upon how many arguments you send it, completely ignoring missing arguments natively.
TypeScript must account for this by establishing multiple Call Signatures known as Function Overloads.
Writing an Overload
To overload a function, you write multiple parameter variations sequentially without a body, followed finally by a single "Implementation" body that wraps all the previous types together natively (often utilizing unions or any).
// 1. First Overload Signature
function makeDate(timestamp: number): Date;
// 2. Second Overload Signature
function makeDate(m: number, d: number, y: number): Date;
// 3. The Actual Implementation Signature (Must cover ALL variations!)
function makeDate(mOrTimestamp: number, d?: number, y?: number): Date {
if (d !== undefined && y !== undefined) {
return new Date(y, mOrTimestamp, d);
} else {
return new Date(mOrTimestamp);
}
}
// Test cases
const d1 = makeDate(12345678); // Valid: Matches Override 1
const d2 = makeDate(5, 5, 5); // Valid: Matches Override 2
// const d3 = makeDate(1, 3); // ERROR! No overload exists for exactly 2 arguments!
Important: The implementation signature (the final one with the code block logic inside) is physically hidden from the outside world. If external code tries to call
makeDate(1, 2), the TS compiler will only read the first two Overloads and will correctly crash because neither overload perfectly matches two explicit arguments.