Advertisement
Advanced TypeScript, Function Types, Overloads & Optional/Default Parameters

How do you write a generic function type with overloads that behave differently based on a literal argument value?

Short answer

Combine overload signatures with specific literal parameter types for each variant, letting the return type or accepted shape change based on that literal — commonly used for APIs like document.createElement, where the tag name literal determines the specific returned element…

Save TypeScript mock interview
Advertisement
AModel answer
Combine overload signatures with specific literal parameter types for each variant, letting the return type or accepted shape change based on that literal — commonly used for APIs like document.createElement, where the tag name literal determines the specific returned element type.
function createElement(tag: 'a'): HTMLAnchorElement;
function createElement(tag: 'img'): HTMLImageElement;
function createElement(tag: string): HTMLElement {
  return document.createElement(tag);
}
const link = createElement('a'); // typed as HTMLAnchorElement
Real-world example
Precisely typing a factory function whose return shape depends on a specific string literal argument, like DOM element creation.
Likely follow-ups
  • Could this same effect be achieved with a single generic function and conditional types instead of overloads?
Related topics