TypeScript
/Advanced
Function Overloading
Definition
Providing multiple function type signatures for the exact same function name, allowing it to accept different combinations of arguments and return different types based on those arguments.
Explain Like I'm New
Overloading is a multi-tool pocket knife. To the user, it is one single tool called 'Cut'. But if they pass it a piece of paper, it acts like scissors. If they pass it a piece of wood, it acts like a saw. The function signature changes based on what you give it.
Real World Example
The DOM `document.createElement()` function. If you pass 'canvas', TS knows it returns an `HTMLCanvasElement`. If you pass 'div', it returns an `HTMLDivElement`.
Common Use Cases
- •Complex utility functions
- •Functions that can take either a single item or an array of items
Interactive Example
// 1. Overload Signatures (No function body, just types) function makeDate(timestamp: number): Date; function makeDate(m: number, d: number, y: number): Date; // 2. Implementation Signature (Must be broad enough to handle all overloads) function makeDate(mOrTimestamp: number, d?: number, y?: number): Date { if (d !== undefined && y !== undefined) { return new Date(y, mOrTimestamp - 1, d); // Months are 0-indexed } else { return new Date(mOrTimestamp); } } const d1 = makeDate(12345678); // Uses overload 1 const d2 = makeDate(5, 5, 2025); // Uses overload 2 // ERROR: No overload expects 2 arguments! // const d3 = makeDate(5, 5);
Interview Questions
basic
- How many implementation bodies does an overloaded function have?
intermediate
- What is the 'Implementation Signature'?
advanced
- Why is function overloading in TS fundamentally different from overloading in Java/C#?