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

← All TypeScript Developer questions