Function Overloads
Functions and Types•Section 2 of 2•intermediate
Topic Overview
Take your time to understand each concept. Practice with the examples below!
Function overloads let you create flexible functions that can handle different types of inputs while maintaining type safety. It's like having multiple versions of the same function!
What are Function Overloads? Function overloading allows one function to have multiple "signatures" - different ways it can be called. TypeScript will figure out which version you're using based on the arguments.
Why Use Overloads?
- •Flexibility:One function name, multiple behaviors
- •Type safety:Each overload is fully typed
- •Better developer experience:Clear IntelliSense for each version
- •API design:Create intuitive, flexible interfaces
How Overloads Work:
1. Define multiple signatures (what users see) 2. Implement one function (handles all cases) 3. TypeScript matches calls to signatures 4. Implementation must handle all cases
Common Patterns:
- •Different parameter counts:func(a) or func(a, b)
- •Different parameter types:func(string) or func(number)
- •Different return types based on input
- •Optional parameters with different behaviors
Real-World Examples:
- •createElement:Can create different HTML elements
- •Array.find:Returns element or undefined
- •jQuery:$("selector") or $(element)
- •Date constructor:new Date() or new Date(string) or new Date(year, month)
Overloads vs Union Types:
- •Overloads:When behavior changes based on input types
- •Union types:When handling multiple types the same way
- •Overloads provide better IntelliSense
- •Union types are simpler for basic cases
Best Practices:
- •Order matters:Most specific first, general last
- •Keep overloads simple and clear
- •Document each overload's purpose
- •Test all overload combinations
- •Consider if union types would be simpler
Example
// Function overload signaturesfunction combine(a: string, b: string): string;function combine(a: number, b: number): number;function combine(a: string[], b: string[]): string[];// Implementation signaturefunction combine(a: any, b: any): any { if (typeof a === 'string' && typeof b === 'string') { return a + b; } else if (typeof a === 'number' && typeof b === 'number') { return a + b; } else if (Array.isArray(a) && Array.isArray(b)) { return a.concat(b); } throw new Error('Invalid arguments');}// Usage examplesconst stringResult = combine("Hello, ", "World!");const numberResult = combine(10, 20);const arrayResult = combine(["a", "b"], ["c", "d"]);console.log(stringResult); // "Hello, World!"console.log(numberResult); // 30console.log(arrayResult); // ["a", "b", "c", "d"]// More complex overload examplefunction processValue(value: string): string;function processValue(value: number): number;function processValue(value: boolean): string;function processValue(value: string | number | boolean): string | number { if (typeof value === 'string') { return value.toUpperCase(); } else if (typeof value === 'number') { return value * 2; } else { return value ? 'TRUE' : 'FALSE'; }}console.log(processValue("hello")); // "HELLO"console.log(processValue(5)); // 10console.log(processValue(true)); // "TRUE"