Sub topic 3
TypeScript Overloads on Methods and Type Declarations
Assume you know unions, literal types, type narrowing, functions, classes, and interfaces. This chapter focuses on placing overloads outside standalone functions and on avoiding common mistakes.
Overloads on class methods
A method can have multiple overload signatures followed by one implementation signature. The implementation parameter must accept every argument shape declared by the overloads.
class Registry {
private items = ["a", "b", "c"];
get(index: number): string | undefined;
get(predicate: (item: string) => boolean): string | undefined;
get(arg: number | ((item: string) => boolean)): string | undefined {
return typeof arg === "number"
? this.items[arg]
: this.items.find(arg);
}
}
const registry = new Registry();
registry.get(1);
registry.get((item) => item === "c");Callers see only the overload signatures. The implementation signature exists to type the method body and is not a callable option by itself.
Overloads in interfaces, type aliases, and ambient declarations
An interface can describe an overloaded function with multiple call signatures. A type alias can use the same call-signature syntax.
interface Formatter {
(value: number): string;
(value: Date, locale: string): string;
}
type Parser = {
(input: string): number;
(input: string[]): number[];
};
declare const format: Formatter;
declare const parse: Parser;
format(3);
format(new Date(), "en-US");
parse("42");
parse(["1", "2"]);An ambient declaration uses declare when the implementation exists elsewhere, such as in a JavaScript library.
declare function parseValue(input: string): number;
declare function parseValue(input: string[]): number[];Pitfalls: unchecked bodies, inference, and over-specific signatures
TypeScript checks that the implementation signature can accept each overload, but it does not fully prove that the body returns the correct result for every case. Narrow values carefully and test runtime behavior.
When overloads are used for inference, TypeScript commonly uses the last overload signature, usually the most general one. Keep signatures ordered from specific to general, and do not expect a union argument to match separate overloads unless you declare a union overload.
Use a union when all inputs have the same return type. Use a generic when the return type follows the input type. Overloads are best when argument shapes produce meaningfully different results.
Exercise
What overload must be added so that getValue(value) accepts string | number when separate string and number overloads already exist?
Show answer
Add an overload whose parameter is string | number, and give it the appropriate combined return type.