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…
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 HTMLAnchorElementReal-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