Sub topic 6
Overloads on Class Methods
Assume you know basic TypeScript types, unions, literal types, classes, interfaces, and type narrowing with typeof and Array.isArray.
A class method can have several valid call shapes. Each shape can provide a different parameter type or return type. TypeScript models these shapes with method overloads.
An overload has two parts:
- Overload signatures describe the calls that other code may make.
- The implementation signature describes the single method body that handles those calls.
The implementation signature must be compatible with every overload, but callers cannot use it directly.
A method with two call shapes
Suppose a registry stores strings. Callers should be able to retrieve an item either by its numeric index or by a predicate function.
class Registry {
private items = ["alpha", "beta", "gamma"];
get(index: number): string | undefined;
get(predicate: (item: string) => boolean): string | undefined;
get(
argument: number | ((item: string) => boolean)
): string | undefined {
if (typeof argument === "number") {
return this.items[argument];
}
return this.items.find(argument);
}
}
const registry = new Registry();
const first = registry.get(0);
// string | undefined
const match = registry.get((item) => item.startsWith("g"));
// string | undefined
// Error: no overload matches this call.
// registry.get("beta");The first two get declarations are overload signatures. They have no method body. The third declaration contains the implementation body.
The implementation accepts a union:
number | ((item: string) => boolean)The body narrows that union with typeof. When the argument is not a number, TypeScript knows it must be the predicate function.
This arrangement gives callers a clear API while keeping one implementation internally.
The implementation signature is hidden
The implementation signature is used to check the method body. It does not become an additional public overload.
class Parser {
parse(text: string): string[];
parse(lines: string[]): string[];
parse(input: string | string[]): string[] {
return Array.isArray(input) ? input : input.split(",");
}
}
const parser = new Parser();
parser.parse("a,b");
parser.parse(["a", "b"]);
// Error: the implementation signature is not visible.
// parser.parse("a", "b");The implementation accepts string | string[], but it does not allow arbitrary calls that might seem compatible with that union. Only the declared overload signatures determine what callers can write.
This separation is useful because the public API can be narrower than the internal handling logic. It also means you must declare every supported public call shape explicitly.
Matching overloads in a method
The compiler checks a call against the overload signatures from top to bottom. The first compatible signature determines the type returned to the caller.
class ValueStore {
private value: string | number = "ready";
read(): string;
read(asNumber: true): number;
read(asNumber?: true): string | number {
if (asNumber) {
return typeof this.value === "number"
? this.value
: Number(this.value);
}
return String(this.value);
}
}
const store = new ValueStore();
const text = store.read();
// string
const number = store.read(true);
// numberHere, the overload with true tells TypeScript that read(true) returns a number. The implementation still returns the broader type string | number, because it must support both behaviors.
The implementation return type does not improve the return type seen by callers. The overload signatures provide that information.
| Declaration | Purpose | Column |
|---|---|---|
| `read(): string` | Describes a public call with no argument | |
| `read(true): number` | Describes a public call with `true` | |
| `read(asNumber?: true): string \ | number` | Implements both calls |
Put more specific overloads before more general ones. A general overload can otherwise capture a call before the specific overload gets a chance to provide a precise result.
Narrowing `this` inside the implementation
A method implementation often needs to narrow its argument before using it. The narrowing must account for every type named by the overloads.
class Collection {
private values = [10, 20, 30];
find(index: number): number | undefined;
find(test: (value: number) => boolean): number | undefined;
find(
argument: number | ((value: number) => boolean)
): number | undefined {
if (typeof argument === "number") {
return this.values[argument];
}
return this.values.find(argument);
}
}The method uses this.values in both branches. TypeScript also checks that the method body returns a value compatible with every overload.
A common mistake is to write an implementation that is too narrow:
class BrokenCollection {
find(index: number): number | undefined;
find(test: (value: number) => boolean): number | undefined;
// Error: this implementation cannot handle the predicate overload.
find(index: number): number | undefined {
return [10, 20, 30][index];
}
}The second overload promises that a predicate is supported, but the implementation only accepts numbers. The implementation parameter must be broad enough to accept every overload input.
> callout note > Treat overload signatures as promises. The implementation must safely handle every promised input, even when the compiler cannot verify all of the runtime behavior for you.
Overloads and inheritance
An overloaded method is part of a class's public contract. A subclass that overrides it should preserve the supported call shapes.
class AnimalShelter {
adopt(name: string): string;
adopt(id: number): string;
adopt(value: string | number): string {
return typeof value === "number"
? `Adopted animal #${value}`
: `Adopted ${value}`;
}
}
class DogShelter extends AnimalShelter {
adopt(name: string): string;
adopt(id: number): string;
adopt(value: string | number): string {
const label = typeof value === "number"
? `dog #${value}`
: `dog named ${value}`;
return `Adopted ${label}`;
}
}
const shelter = new DogShelter();
shelter.adopt("Rex");
shelter.adopt(7);Repeat the overload signatures in the subclass when the subclass provides its own implementation. This keeps the subclass's visible method type clear and prevents callers from losing the supported call shapes.
Overriding becomes more difficult when a subclass changes parameter or return types. A narrower parameter type may reject calls that are valid through the base class. Design the base overloads carefully before extending the class.
When a union is simpler
Overloads are useful when the argument shape determines a more precise return type or when the call forms have distinct meanings. They are unnecessary when every call has the same return type.
class TextTools {
length(value: string | readonly unknown[]): number {
return value.length;
}
}This single signature is easier to read than two overloads:
class VerboseTextTools {
length(value: string): number;
length(value: readonly unknown[]): number;
length(value: string | readonly unknown[]): number {
return value.length;
}
}Use a union when the method behaves the same way and returns the same type for every accepted input. Use overloads when the public call shapes have different meanings or when each shape deserves a more precise return type.
Exercise
Exercise
Write a Converter class with overloads for convert(value: string): number and convert(value: number): string. The implementation should use typeof to convert a string with Number and a number with String.
Show answer
class Converter {
convert(value: string): number;
convert(value: number): string;
convert(value: string | number): number | string {
return typeof value === "string" ? Number(value) : String(value);
}
}