TypeScript Developer interview question · Most asked
How do function overloads work in TypeScript and when are they better than unions?
Summary
Overloads declare multiple call signatures for one implementation, letting the return type depend on the argument types. The implementation signature must be compatible with all overloads and isn't visible to callers.
Longer Answer
Use overloads when the output type depends on input in ways a union can't express (e.g., parse(x: string): Date; parse(x: number): Date[]). Often a generic or conditional return type is simpler. Overload order matters: TypeScript picks the first matching signature.
Code Example
function createElement(tag: "a"): HTMLAnchorElement;
function createElement(tag: "canvas"): HTMLCanvasElement;
function createElement(tag: string): HTMLElement;
function createElement(tag: string): HTMLElement {
return document.createElement(tag);
}
const c = createElement("canvas"); // HTMLCanvasElement
Key Points
- Multiple call signatures, one implementation
- Implementation signature hidden
- Order matters
- Consider generics/conditional types first
More most-asked TypeScript Developer questions
- Explain `any`, `unknown` and `never`.
- What are the differences between `interface` and `type` aliases?
- What is structural typing in TypeScript?
- What is type narrowing and what techniques does TypeScript support?
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is TypeScript and what problems does it solve?