Sub topic 7
Overloads in Interfaces, Type Aliases, and Ambient Declarations
This chapter assumes that you know basic TypeScript types, unions, literal types, functions, type narrowing, classes, and interfaces. It focuses on describing overloaded functions when the implementation is somewhere else, or when you want to store a callable shape in a type.
Function overloads are useful when a function accepts different argument shapes and the return type depends on the shape of the arguments. Interfaces, type aliases, and ambient declarations can describe those call shapes without containing the implementation.
Overloads in an interface
An interface can contain multiple call signatures. A call signature describes how a value can be called. It has parameters and a return type, but no function body.
interface Formatter {
(value: number): string;
(value: Date, locale: string): string;
}Formatter describes a callable value with two permitted forms:
- One number argument.
- A
Dateand a locale string.
A value assigned to Formatter must support both forms:
const format: Formatter = (value: number | Date, locale?: string): string => {
if (typeof value === "number") {
return value.toFixed(2);
}
return value.toLocaleDateString(locale);
};
const price = format(12.5); // string
const date = format(new Date(), "en-US"); // string
// format("12.5"); // Error
// format(new Date()); // ErrorThe implementation is an arrow function, so it does not have overload declarations in the same way as a function declaration. Instead, the variable's type supplies the overloads. The function assigned to that variable must be compatible with every call signature in the interface.
The implementation parameters often need to use a union and an optional parameter. Inside the body, type narrowing determines which behavior to use.
Overloads with a type alias
A type alias can also describe an overloaded callable value. Use multiple call signatures inside an object type:
type Parser = {
(input: string): number;
(input: string[]): number[];
};
const parse: Parser = (input: string | string[]): number | number[] => {
if (Array.isArray(input)) {
return input.map((item) => Number(item));
}
return Number(input);
};
const one = parse("42"); // number
const many = parse(["1", "2"]); // number[]The two signatures tell callers which result they receive. A string produces a number, while an array of strings produces an array of numbers.
The implementation's return type must be broad enough to cover both results. The public type still exposes the precise result for each call. Callers do not see number | number[] when they call parse; they see the return type selected by the matching overload.
The same syntax works when a type alias is combined with other object properties:
type Search = {
(query: string): Promise<string[]>;
(query: string, limit: number): Promise<string[]>;
source: "local" | "remote";
};A value of type Search must be callable in both ways and must also have a source property. This pattern is useful for function objects that carry configuration or metadata.
Interfaces and type aliases compared
Both forms can represent overloaded callables. Choose based on how you use the type.
| Form | Useful when | Example |
|---|---|---|
| Interface | You want an extendable named contract | `interface Formatter { (x: number): string }` |
| Type alias | You want to compose the callable shape with unions or intersections | `type Parser = { (x: string): number }` |
| Function declaration | You own the implementation and want overload syntax beside it | `function parse(x: string): number` |
An interface can be extended, while a type alias can be combined with intersections and other type expressions. The call behavior is similar once a value has either type.
Ambient declarations
An ambient declaration describes code that exists at runtime but is implemented outside the current TypeScript file. Ambient declarations commonly appear in .d.ts files, which are declaration files.
Use the declare keyword to declare an overloaded function without providing a body:
declare function parse(input: string): number;
declare function parse(input: string[]): number[];The declarations tell TypeScript how callers may use parse. They do not create a JavaScript function. A separate JavaScript library, runtime API, or compiled module must provide the actual implementation.
const value = parse("42"); // number
const values = parse(["1", "2"]); // number[]
// parse(42); // ErrorA declaration file might describe a library exported by another module:
// analytics.d.ts
export function track(event: string): void;
export function track(event: string, properties: Record<string, string>): void;Code importing this declaration receives overload checking:
import { track } from "./analytics";
track("page_view");
track("purchase", { product: "book" });
// track("purchase", 123); // ErrorThe declaration file does not verify the runtime implementation. If the JavaScript library accepts different arguments than the declaration promises, TypeScript cannot detect that mismatch from the declaration alone.
Assigning overloaded functions
A regular overloaded function can be assigned to an interface or type alias with matching call signatures:
function getValue(key: "name"): string;
function getValue(key: "count"): number;
function getValue(key: "name" | "count"): string | number {
return key === "name" ? "Ada" : 3;
}
type Getter = {
(key: "name"): string;
(key: "count"): number;
};
const getter: Getter = getValue;
const name = getter("name"); // string
const count = getter("count"); // numberThe public overloads of getValue and Getter agree. The implementation signature, ("name" | "count") => string | number, is wider and remains hidden from callers.
This separation is useful when a library implementation is complex but its public API should stay precise.
Pitfalls and inference
An interface or type alias checks the assigned function against all its signatures, but it does not inspect a body that is hidden in an ambient declaration. Keep declaration files synchronized with the runtime library.
Overload order also matters for ordinary overloaded declarations. TypeScript checks signatures from top to bottom and uses the first applicable signature. Put specific signatures before general signatures:
interface Convert {
(value: "yes" | "no"): boolean;
(value: string): string;
}The first signature is more specific for "yes" and "no". A general signature placed first could prevent callers from receiving the more precise result.
When TypeScript infers a type from an overloaded function, it often uses the last overload signature. This matters with utility types such as ReturnType:
function read(id: number): string;
function read(id: string): number;
function read(id: number | string): string | number {
return typeof id === "number" ? `item-${id}` : id.length;
}
type ReadResult = ReturnType<typeof read>; // string | numberThe implementation signature is not directly callable, but the final overload influences this kind of type-level inference. Do not rely on ReturnType to preserve every input-to-output relationship. For that relationship, explicit overload calls or a generic type may be more precise.
Exercise
Define a callable type named Lookup with one overload accepting a numeric ID and returning User, and another accepting an array of numeric IDs and returning User[]. What must an implementation assigned to Lookup handle?
Show answer
It must handle both number and number[] inputs and return either User or User[]. The two call signatures provide the precise result type to callers.