function parse(input: string): number;
function parse(input: number): string;
function parse(input: string | number) {
return typeof input === "string" ? Number(input) : String(input);
}
const n = parse("42"); // number
const s = parse(42); // string
Overloads give one function several call signatures. Use them when the return type depends on the argument type. If the return type does not change, a union parameter is simpler.
How they work:
- You write the overload signatures first.
- Then you write one implementation. Its signature must be compatible with all the overloads.
- Callers see only the overloads, not the implementation signature.
Why use them? With a single union signature, parse("42") would return string | number, and the caller would have to narrow it. With overloads, each call gets the exact type: parse("42") gives number.
The downsides:
- TypeScript does not check the body against each overload one by one.
- A caller with a
string | numbervalue cannot callparse, unless you add an overload for the union.
Generics or conditional types are another option.
- Overloads are several signatures plus one compatible implementation.
- Code outside the function cannot call the implementation signature.
- Use overloads when the return type depends on the input type.
- A union argument like
string | numberneeds its own overload. - Prefer a union parameter when the output type does not change.
Read more