Sub topic 6
Overloads on Class Methods
What this chapter assumes
You should already be comfortable with these ideas from earlier chapters:
- Writing overload signatures followed by one implementation signature.
- The implementation signature is invisible to callers.
- The compiler tries overloads from top to bottom and uses the first match.
- Basic classes, interfaces, and narrowing with
typeofandArray.isArray.
This chapter applies those rules to class members. Methods, constructors, and static methods can all be overloaded. Classes add a few constraints that free functions do not have: shared modifiers, inheritance, and this.
A first method overload
An overloaded method looks like an overloaded function, written inside the class body. You write the overload signatures first, with no bodies. The implementation signature and body come immediately after.
class Store {
protected data = new Map<string, string>([
["a", "1"],
["b", "2"],
]);
get(key: string): string | undefined;
get(keys: string[]): (string | undefined)[];
get(arg: string | string[]): string | undefined | (string | undefined)[] {
return typeof arg === "string"
? this.data.get(arg)
: arg.map((k) => this.data.get(k));
}
}
const store = new Store();
const one = store.get("a"); // string | undefined
const many = store.get(["a", "z"]); // (string | undefined)[]A single union signature get(arg: string | string[]): string | undefined | (string | undefined)[] would also compile. But callers would then get the full union back and would have to narrow it themselves, even though they know which shape they passed. The overloads tie each argument shape to its own return type.
Callers see only the two overload signatures. Calling store.get(5) is an error, and so is passing a value typed as string | string[], because neither overload accepts the union. If you need to accept that union, add a third overload for it.
The modifier rules
Within a class, all signatures in one overload group must agree on several modifiers. The group consists of the overloads plus the implementation. The compiler reports a mismatch on the signature that disagrees.
| Rule | Typical error message |
|---|---|
| All signatures have the same accessibility (`public`, `protected`, `private`) | Overload signatures must all be public, private or protected. |
| All signatures are either optional (`?`) or required | Overload signatures must all be optional or required. |
| All signatures are either `static` or instance members | Function overload must be static. / Function overload must not be static. |
| The implementation immediately follows the last overload | Function implementation is missing or not immediately following the declaration. |
| Each overload is compatible with the implementation | This overload signature is not compatible with its implementation signature. |
The "immediately following" rule has a practical effect. You cannot put another member between two overloads of the same method, and you cannot split a group across the class body. Keep each group together.
class Broken {
// Error: Overload signatures must all be public, private or protected.
public run(x: string): void;
private run(x: number): void;
run(x: string | number): void {}
}The accessibility modifier is the only one worth worrying about in everyday code. Pick it once and write it on every signature.
The diagram below shows the checks a class overload group goes through, and what callers end up seeing.
Returning `this` from overloads
Fluent methods that return this work with overloads. Each overload can declare : this, so subclasses keep their own type in a chain.
This pattern is common for event-style APIs, where the first argument is a string literal that selects the payload type.
type ClickEvent = { x: number; y: number };
type KeyEvent = { key: string };
class Bus {
private handlers: Record<string, Array<(payload: any) => void>> = {};
on(event: "click", handler: (payload: ClickEvent) => void): this;
on(event: "key", handler: (payload: KeyEvent) => void): this;
on(event: string, handler: (payload: any) => void): this {
(this.handlers[event] ??= []).push(handler);
return this;
}
emit(event: "click", payload: ClickEvent): void;
emit(event: "key", payload: KeyEvent): void;
emit(event: string, payload: unknown): void {
for (const handler of this.handlers[event] ?? []) {
handler(payload);
}
}
}
const bus = new Bus();
bus
.on("click", (p) => console.log(p.x, p.y))
.on("key", (p) => console.log(p.key));
bus.emit("click", { x: 1, y: 2 });
// bus.emit("click", { key: "a" }); // Error: no overload matches this call
// bus.on("scroll", () => {}); // Error: "scroll" is not a known eventThe contextual typing works as you would hope. In .on("click", (p) => ...), the compiler matches the literal "click" against the first overload and types p as ClickEvent.
The implementation uses any for the stored handlers. That is a deliberate loosening: the implementation body is where the types are not enforced, and the overloads are the contract. Keep the loose part private and small.
A generic alternative
When each overload differs only by a key from a lookup table, a generic method with a constraint is shorter and easier to extend. Adding an event becomes a one-line change to the Events type.
interface Events {
click: { x: number; y: number };
key: { key: string };
}
class TypedBus {
private handlers: Record<string, Array<(payload: any) => void>> = {};
on<K extends keyof Events>(event: K, handler: (payload: Events[K]) => void): this {
(this.handlers[event] ??= []).push(handler);
return this;
}
}
new TypedBus().on("key", (p) => console.log(p.key.toUpperCase()));Prefer this version when the cases are uniform. Prefer overloads when the cases differ in argument count or in the structure of the parameters, as in the Point constructor below.
Constructor overloads
Constructors can be overloaded with the same pattern. Two differences matter:
- Constructor overload signatures have no return type. The result is always an instance of the class.
- Property initialization is checked in the implementation body, so every branch must assign every required property.
class Point {
x: number;
y: number;
constructor(x: number, y: number);
constructor(coords: [number, number]);
constructor(coords: { x: number; y: number });
constructor(a: number | [number, number] | { x: number; y: number }, b = 0) {
if (typeof a === "number") {
this.x = a;
this.y = b;
} else if (Array.isArray(a)) {
this.x = a[0];
this.y = a[1];
} else {
this.x = a.x;
this.y = a.y;
}
}
}
const p1 = new Point(1, 2);
const p2 = new Point([3, 4]);
const p3 = new Point({ x: 5, y: 6 });
// new Point(1); // Error: no overload takes exactly one numberThe default b = 0 in the implementation makes the second parameter optional there. Callers still cannot omit it when passing a number, because the first overload requires both arguments. Inside the implementation, the default means b is a plain number, so you avoid a non-null assertion.
If a class has many construction paths, consider named static factories instead of a long constructor overload list. Names such as Point.fromArray document themselves, and each factory can have a precise signature.
Static method overloads
Static methods follow the same rules as instance methods, with one extra requirement. Every signature in the group, including the implementation, must be static.
class Color {
private constructor(
readonly r: number,
readonly g: number,
readonly b: number,
) {}
static from(hex: string): Color;
static from(r: number, g: number, b: number): Color;
static from(a: string | number, g = 0, b = 0): Color {
if (typeof a === "string") {
const n = parseInt(a.replace("#", ""), 16);
return new Color((n >> 16) & 255, (n >> 8) & 255, n & 255);
}
return new Color(a, g, b);
}
}
const red = Color.from("#ff0000");
const green = Color.from(0, 255, 0);
// Color.from(0, 255); // Error: no overload takes exactly two argumentsMaking the constructor private forces callers through Color.from, so the overloads become the only public way to build a Color.
Overloads and inheritance
When a subclass redeclares a method, the subclass's method type must be assignable to the base class's method type. For overloaded methods, this means every overload in the base class must be matched by some overload in the subclass.
You can add overloads in a subclass. You cannot take them away.
class IndexedStore extends Store {
get(key: string): string | undefined;
get(keys: string[]): (string | undefined)[];
get(index: number): string | undefined;
get(
arg: string | string[] | number,
): string | undefined | (string | undefined)[] {
if (typeof arg === "number") {
return Array.from(this.data.values())[arg];
}
if (typeof arg === "string") {
return super.get(arg);
}
return super.get(arg);
}
}
const indexed = new IndexedStore();
indexed.get("a"); // string | undefined
indexed.get(0); // string | undefinedThe subclass repeats the two inherited overloads and adds a third. The repeat is required. If the subclass declared only get(index: number), TypeScript would report that the property get is not assignable to the same property in the base type, because that single signature cannot stand in for the base overloads.
The calls to super.get resolve against the base class's overloads, not its implementation. That is why the code narrows arg to string and then to string[] before calling. Passing the union would fail for the same reason it fails for outside callers.
Abstract methods
Abstract methods can have overload signatures too. The concrete subclass must then declare the overloads and an implementation.
abstract class Parser {
abstract parse(input: string): number;
abstract parse(input: string[]): number[];
}
class NumberParser extends Parser {
parse(input: string): number;
parse(input: string[]): number[];
parse(input: string | string[]): number | number[] {
return typeof input === "string" ? Number(input) : input.map(Number);
}
}
const n = new NumberParser().parse("42"); // number
const ns = new NumberParser().parse(["1", "2"]); // number[]Implementing an interface
A class that implements an interface with overloaded methods must provide those overloads. A single union signature is not enough, even if it accepts all the inputs, because its return type is too wide for each individual overload.
interface Reader {
read(id: number): string;
read(ids: number[]): string[];
}
class MemoryReader implements Reader {
private rows = ["zero", "one", "two"];
read(id: number): string;
read(ids: number[]): string[];
read(arg: number | number[]): string | string[] {
return typeof arg === "number" ? this.rows[arg] : arg.map((i) => this.rows[i]);
}
}If you replaced the three read lines with only read(arg: number | number[]): string | string[], the compiler would report that MemoryReader incorrectly implements Reader. The interface promises a string for a number argument, and the union signature promises only string | string[].
Overloads and property-style methods
Overloads belong to method declarations. A class property initialized with an arrow function is not a method, so you cannot write overload signatures above it. Instead, give the property an object type with multiple call signatures, then assign a function that is compatible with all of them.
class Formatter {
format: {
(value: number): string;
(value: Date, locale: string): string;
} = (value: number | Date, locale?: string): string =>
typeof value === "number" ? value.toFixed(2) : value.toLocaleDateString(locale);
}
const f = new Formatter();
f.format(3.14159); // "3.14"
f.format(new Date(0), "en-US");Two things differ from a real method. Each instance gets its own copy of the function, and subclasses cannot call it through super, because it is not on the prototype. Use this form only when you need the arrow function's lexical this, for example when the property is passed around as a callback.
The next chapter covers call signatures in interfaces and type aliases in more detail.
Pitfalls specific to classes
The body is not checked against each overload
TypeScript checks that each overload is compatible with the implementation signature. It does not check that the body returns the right type for each overload. The compatibility check is also loose: the overload's return type only needs to be assignable in one direction.
class Box {
read(kind: "text"): string;
read(kind: "size"): number;
read(kind: "text" | "size"): string | number {
return 0; // compiles, but read("text") is typed string and returns 0
}
}
const text: string = new Box().read("text"); // typed string, actually 0This is the main risk of overloads, in classes as elsewhere. The caller trusts the overload and the compiler trusts the implementation. Write a test for each overload, or keep the body to a simple typeof or discriminant branch where each branch visibly matches one overload.
Utility types see only the last overload
Parameters and ReturnType infer from a single signature. When a method has several, they use the last one.
type GetParams = Parameters<Store["get"]>; // [keys: string[]]
type GetReturn = ReturnType<Store["get"]>; // (string | undefined)[]That surprises people who build wrappers, mocks, or decorators from Store["get"]. A wrapper typed this way accepts only the last overload's arguments. If you need a wrapper that preserves all overloads, declare the wrapper with the same overload list, or give the method an interface type with explicit call signatures.
Order still matters
The top-to-bottom resolution rule applies to methods. If you put a general overload before a specific one, the specific overload is never chosen. For example, get(key: unknown): unknown placed above get(key: string): string swallows every call. Keep the narrowest signature first.
Overload counts add up in subclasses
Because subclasses must repeat the base overloads to add new ones, a deep hierarchy can end up with the same group copied several times. When you notice this, consider whether a generic base class or a lookup-table type would express the family better.
Choosing between overloads and alternatives on a class
| Situation | Better choice |
|---|---|
| Return type is the same for every argument shape | One signature with a union parameter |
| Cases differ only by a key into a type table | Generic method with `K extends keyof Table` |
| Argument counts differ, and each count has its own meaning | Overloads |
| Parameter shapes map to different return types | Overloads |
| Many unrelated construction paths | Named static factories |
| Behavior must be a per-instance callback | Property with call-signature type |
Summary
- Method, constructor, and static overloads use the same pattern as function overloads: signatures first, then one implementation.
- Every signature in a group must share the same accessibility, optionality, and static-ness, and the group must be contiguous.
- Fluent overloads can return
this, so subclass chains keep their own type. - A subclass can add overloads to an inherited method but must repeat the inherited ones.
- A class implementing an overloaded interface method must declare the overloads. A union signature does not satisfy them.
- The implementation body is not checked per overload, and
ParametersandReturnTypesee only the last signature.
Exercise
A class has get(key: string): string; and get(key: number): string; followed by private get(key: string | number): string { ... }. The compiler rejects it. What is wrong and how do you fix it?
Show answer
The implementation is private while the overloads are public, and all signatures in a group must have the same accessibility. Remove private from the implementation, or add private to every signature. The implementation signature is invisible to callers either way, so it normally takes the same modifier as the overloads.
Exercise
class Base { find(id: number): string; find(ids: number[]): string[]; find(a: number | number[]): string | string[] { return typeof a === "number" ? String(a) : a.map(String); } }. A subclass declares only find(id: number): string { return "x"; }. Does it compile? Why or why not?
Show answer
No. The subclass's method type must be assignable to the base class's method type, which includes the find(ids: number[]): string[] overload. A single-signature method cannot stand in for that overload, so the compiler reports that find is not assignable to the same property in the base type. The subclass must repeat both inherited overloads, and it may add more.
Exercise
What does Parameters<Store["get"]> produce for the Store class in this chapter, and why might that surprise a developer writing a wrapper?
Show answer
It produces [keys: string[]], because utility types that infer from a function type use the last overload. A wrapper typed with it would accept only the array form and would reject calls like get("a"), even though the original method accepts them.