Sub topic 2
How the Compiler Picks an Overload
Assume you know basic TypeScript unions, literal types, function calls, and type narrowing. Overload resolution is the process TypeScript uses to choose one overload signature for a call.
Overload resolution
TypeScript checks overload signatures from top to bottom. It selects the first compatible signature and uses that signature's return type for the call. The implementation signature is not available to callers.
function format(value: Date): string;
function format(value: string): string;
function format(value: Date | string): string {
return value instanceof Date ? value.toISOString() : value.trim();
}
const dateText = format(new Date()); // string
const nameText = format(" Ada "); // stringWhen overloads produce different return types, the selected signature controls the result.
function parse(value: string): number;
function parse(value: string[]): number[];
function parse(value: string | string[]): number | number[] {
return Array.isArray(value) ? value.map(Number) : Number(value);
}
const one = parse("42"); // number
const many = parse(["1", "2"]); // number[]Put specific overloads before general ones. A general signature can accept a value before TypeScript reaches a more useful specific signature.
function inspect(value: string): string;
function inspect(value: unknown): unknown;
function inspect(value: unknown): unknown {
return value;
}
const text = inspect("hello"); // string
const anything = inspect(123); // unknownWhen not to use overloads
Use a union when the return type does not depend on the argument type. Use a generic when the function preserves a type relationship.
| Need | Prefer |
|---|---|
| One return type for several inputs | Union |
| Return type follows an input type | Generic |
| Distinct call shapes and return types | Overloads |
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const value = first(["a", "b"]); // string | undefinedOverloads are also a poor fit when optional parameters describe one simple call shape. Prefer one signature if callers receive the same result regardless of which arguments they provide.
Exercise
Which overload does TypeScript use for the call pick("x") when pick(value: string): string appears before pick(value: unknown): unknown?
Show answer
It uses the first overload because it is the first compatible signature, so the result has type string.