Real-World Overload Examples
You'll learn: How overloads appear in real-world TypeScript code, from DOM APIs to popular libraries, and when you should reach for them in your own projects.
Where You've Already Seen Overloads
Even if you didn't know it, you've been using overloaded functions every time you work with the DOM or popular libraries. TypeScript's type definitions are filled with them because they model the flexible APIs JavaScript developers expect.
DOM API Overloads
The createElement function in the browser has overloads that return different element types based on the tag name you pass:
// Returns HTMLDivElement
const div = document.createElement('div');
// Returns HTMLCanvasElement
const canvas = document.createElement('canvas');
// Returns HTMLElement (generic fallback)
const custom = document.createElement('my-custom-tag');
Behind the scenes, TypeScript uses overloads to provide specific types for known tags while falling back to a generic type for unknown ones.
Library Overloads
Many popular libraries use overloads to handle optional parameters elegantly. For instance, an event emitter might work like this:
// With callback
emitter.on('data', (data) => console.log(data));
// Without callback, returns a promise
await emitter.on('data');
When to Use Overloads in Your Code
Reach for overloads when:
- Your function returns different types based on input types
- You have multiple valid calling patterns that can't be expressed cleanly with optional or union parameters
- You're building a public API where precise types improve developer experience
Avoid overloads when a union type or optional parameters would be clearer. Remember: overloads add complexity, so use them only when they genuinely improve type safety and usability.
Key Takeaway: Overloads are common in DOM APIs and libraries to handle flexible calling patterns—use them in your own code when simpler approaches (unions, optionals) don't provide precise enough types.