Sub topic 8
Pitfalls: Unchecked Bodies, Inference, and Over-Specific Signatures
Assume you know basic TypeScript unions, literal types, typed functions, narrowing with typeof and Array.isArray, and basic classes and interfaces. This chapter focuses on cases where overloads compile but still mislead callers or produce surprising types.
Overloads have two audiences:
- The overload signatures describe what callers are allowed to do.
- The implementation signature describes how the function body receives and processes those calls.
These two descriptions must agree. TypeScript checks that the implementation can support the overload signatures, but it cannot prove that the body follows every promise at runtime.
The implementation body is not fully checked against each overload
Consider this function:
type Config = {
name: string;
};
function parseConfig(text: string): Config;
function parseConfig(text: string[]): Config[];
function parseConfig(input: string | string[]): Config | Config[] {
if (typeof input === "string") {
return { name: JSON.parse(input).name };
}
// This is allowed because Config is part of the implementation return type.
// However, the string[] overload promises Config[].
return { name: input[0] };
}
const configs = parseConfig(["first", "second"]);
// TypeScript says Config[], but the function returns one Config object.The implementation signature allows either Config or Config[]. That return type is broad enough for the body, but it does not force the array branch to return Config[]. The overload is therefore an unchecked promise.
A safer implementation returns the correct shape in every branch:
type Config = {
name: string;
};
function parseConfig(text: string): Config;
function parseConfig(text: string[]): Config[];
function parseConfig(input: string | string[]): Config | Config[] {
if (typeof input === "string") {
return { name: JSON.parse(input).name };
}
return input.map((name) => ({ name }));
}
console.log(parseConfig('{"name":"main"}'));
console.log(parseConfig(["first", "second"]));You can also use runtime validation when input comes from a file, network request, or user. A type annotation does not validate JSON. The implementation must check values that are not already trusted by TypeScript.
Overload resolution and the last-signature rule
For an ordinary function call, TypeScript checks overloads from top to bottom and chooses the first compatible signature.
function format(value: Date): string;
function format(value: string | number): string;
function format(value: Date | string | number): string {
if (value instanceof Date) {
return value.toISOString();
}
return String(value);
}
format(new Date()); // Date overload
format("total"); // string | number overload
format(42); // string | number overloadThe order matters when signatures overlap. Put the more specific signature first:
function describe(value: "ready"): "the system is ready";
function describe(value: string): string;
function describe(value: string): string {
return value === "ready" ? "the system is ready" : value;
}
const message = describe("ready");
// Type: "the system is ready"If the general string overload came first, "ready" would match it and the result would be typed only as string.
However, type-level inference does not perform a fresh overload search for every possible argument. Utilities such as ReturnType usually inspect the last overload signature.
function lookup(id: number): { id: number };
function lookup(name: string): { id: number } | undefined;
function lookup(key: number | string): { id: number } | undefined {
if (typeof key === "number") {
return { id: key };
}
return key === "main" ? { id: 1 } : undefined;
}
type LookupResult = ReturnType<typeof lookup>;
// { id: number } | undefined
// This comes from the last overload signature.The last overload should usually be the broadest public case. Do not assume that ReturnType can represent the exact return type for every possible argument.
Over-specific signatures create fragile APIs
An overload set can be technically precise but difficult to use. Literal-heavy overloads often reject values that are valid at runtime:
function request(method: "GET", path: string): Promise<string>;
function request(method: "POST", path: string, body: string): Promise<string>;
function request(
method: "GET" | "POST",
path: string,
body?: string
): Promise<string> {
return Promise.resolve(`${method} ${path}${body ?? ""}`);
}
const method: "GET" | "POST" = Math.random() > 0.5 ? "GET" : "POST";
// Error: no overload accepts a method that might be either value.
// request(method, "/items");The implementation supports the union, but neither overload accepts it. Add a public overload for the union only if that call shape is meaningful:
function request(method: "GET", path: string): Promise<string>;
function request(method: "POST", path: string, body: string): Promise<string>;
function request(
method: "GET" | "POST",
path: string,
body?: string
): Promise<string>;
function request(
method: "GET" | "POST",
path: string,
body?: string
): Promise<string> {
return Promise.resolve(`${method} ${path}${body ?? ""}`);
}Avoid adding overloads merely to make every implementation detail visible. A large overload list increases maintenance cost, makes ordering significant, and can produce confusing “no overload matches” errors.
Use a union when the return type does not change:
function printId(id: string | number): string {
return String(id);
}Use a generic when the return value preserves a type relationship:
function identity<T>(value: T): T {
return value;
}
const n = identity(10); // number
const text = identity("text"); // stringUse overloads when the argument shape changes the return type or when different argument counts represent distinct, useful call contracts.
A review checklist
Before publishing an overloaded function, check the following:
- Each overload is a call shape that users actually need.
- The implementation parameter types accept every overload’s parameters.
- The implementation return type can represent every overload’s return type.
- Every runtime branch returns the shape promised by its matching overload.
- Specific overloads appear before general overloads.
- The last overload gives sensible results for utilities such as
ReturnType. - A union or generic would not express the same behavior more simply.
- Inputs from outside the type system are validated at runtime.
Exercise
An overloaded function has function read(id: number): User; followed by function read(key: string): User | undefined;. What does ReturnType<typeof read> produce, and why?
Show answer
It produces User | undefined because conditional type inference uses the last overload signature, rather than selecting an overload based on a particular call argument.