Sub topic 7
Overloads in interfaces, type aliases, and ambient declarations
This chapter assumes you can write overloaded function declarations with an implementation signature, as covered earlier in this tutorial. It also assumes you know how interfaces, type aliases, and declare statements work at a basic level.
A function declaration is not the only place an overloaded function can appear. Often you need to describe an overloaded function without writing its body:
- The value is an arrow function, and arrow functions have no overload syntax.
- The function comes from a JavaScript library you are typing.
- A function type is stored in a property or passed as an argument.
TypeScript handles these cases with call signatures in types and with ambient declarations. In both, a list of signatures is the whole description, and no implementation signature exists.
Call signatures: overloads as part of a type
A call signature is a member of an object type that looks like a function header with no name:
interface Formatter {
(value: number): string;
(value: Date, locale: string): string;
}Each line is one overload. An interface with two or more call signatures describes a value you can call in either shape, and the same resolution rules apply as for a function declaration: signatures are tried in order, and the first match wins.
The interface says nothing about how the function is built. You get a value of this type by assigning a function to it:
interface Formatter {
(value: number): string;
(value: Date, locale: string): string;
}
const format: Formatter = (value: number | Date, locale?: string): string => {
if (typeof value === "number") {
return value.toFixed(2);
}
return value.toLocaleDateString(locale);
};
const a = format(3.14159); // string
const b = format(new Date(), "en-US"); // string
// format(new Date()); // Error: no signature accepts a Date with one argumentThe arrow function has one signature, (value: number | Date, locale?: string) => string. The assignment is allowed because each signature in Formatter can be satisfied by that one signature. The number overload passes because the extra parameter is optional. The Date overload passes because Date is part of the union.
This is the usual way to give an arrow function overloads: declare the overloaded type, then annotate the variable with it.
Parameters are not inferred from overloaded types
When a variable's type has exactly one call signature, TypeScript uses it to infer the parameter types of the function you assign. With two or more signatures there is no single signature to borrow from, so inference does not happen:
// Under noImplicitAny (part of strict), this is an error:
// parameters 'value' and 'locale' implicitly have type 'any'.
// const bad: Formatter = (value, locale) => String(value);Write the parameter types in the arrow function yourself.
The assignability check is looser than a function declaration
Compare a function declaration with overloads to a variable assigned an arrow function. The declaration's implementation signature is checked against each overload, and that check is lenient about return types. The assignment above is checked in a stricter way: the function's return type must be assignable to the return type of every signature it is matched against.
That difference matters when the return type depends on the argument:
interface Parser {
(input: string): number;
(input: string[]): number[];
}
// Error: the body returns number | number[], which is not assignable
// to number (first signature) or to number[] (second signature).
// const bad: Parser = (input: string | string[]) =>
// typeof input === "string" ? Number(input) : input.map(Number);
function parseImpl(input: string): number;
function parseImpl(input: string[]): number[];
function parseImpl(input: string | string[]): number | number[] {
return typeof input === "string" ? Number(input) : input.map(Number);
}
const parser: Parser = parseImpl;
const one = parser("42"); // number
const many = parser(["1", "2"]); // number[]For this kind of function the better route is to write a function declaration with overloads and then assign it to the interface type. A type assertion with as Parser also compiles, but it removes the compiler's check.
Type aliases
Anything an interface can say about call signatures, an object type literal in a type alias can say too:
type Serialize = {
(value: number): string;
(value: boolean): "yes" | "no";
};Interface or alias is mostly a style choice here. Use an interface when you want declaration merging (see below). Use an alias when you also need unions, intersections, or mapped types.
Intersections of function types
An intersection of function types also behaves as an overloaded function. The signatures are tried in the order of the intersection:
type Doubler = ((x: number) => number) & ((x: string) => string);
declare const twice: Doubler;
const n = twice(2); // number
const s = twice("a"); // stringThis form is convenient when you build the overloaded type from existing pieces, for example Existing & ((x: Extra) => Result). Note that the order of the operands decides which overload is tried first. If you write the general signature first, it will shadow the specific one.
Callable objects
A call signature can sit next to ordinary properties. This describes a function that also has fields, which is common in JavaScript libraries:
type Counter = {
(): number;
reset(): void;
readonly label: string;
};Add more than one call signature and you get an overloaded callable object. Constructor overloads work the same way, using new (...) signatures in place of call signatures.
Reusing an existing function's overloads with `typeof`
You do not have to restate overloads in a type. typeof someFunction produces a type that keeps every overload:
declare function parse(input: string): number;
declare function parse(input: string[]): number[];
type ParseFn = typeof parse; // both overloads preserved
type Out = ReturnType<typeof parse>; // number[]
type In = Parameters<typeof parse>; // [input: string[]]The last two lines show a limitation. Utility types such as ReturnType and Parameters use conditional types with infer, and inference from an overloaded type looks only at the last signature. If you use these utilities on an overloaded function, put the signature you want them to see last, or write the type by hand.
Ambient declarations
An ambient declaration tells the compiler that something exists without defining it. The keyword is declare. You use it to describe code that lives somewhere the compiler cannot see: a plain JavaScript file, a global provided by the runtime, or a package with no bundled types.
For overloads, ambient context changes one thing: there is no implementation. Every signature is an overload, and the "implementation signature" does not exist because there is no body at all.
declare function parse(input: string): number;
declare function parse(input: string[]): number[];
const n = parse("42"); // number
const ns = parse(["1", "2"]); // number[]The compiler requires the overloads of one function to be adjacent and to agree on modifiers. If some are export and others are not, or some are declare and others are not, it reports an error.
Typing a JavaScript package in a `.d.ts` file
The most common use is a declaration file. Suppose a package tiny-csv exports one parse function whose result depends on a flag:
// tiny-csv.d.ts
declare module "tiny-csv" {
export function parse(input: string): string[][];
export function parse(
input: string,
withHeader: true
): Record<string, string>[];
export function parse(
input: string,
withHeader: boolean
): string[][] | Record<string, string>[];
}The three signatures run from specific to general:
- One argument returns rows of strings.
- A literal
truereturns records keyed by the header names. - A plain
booleanreturns the union, because the compiler cannot know which branch the JavaScript takes.
If you swapped the second and third, a call with true would match the boolean signature first and the precise record type would never be selected. The .d.ts file has no compile-time check against the real JavaScript. If the declared overloads do not match what the package does, the compiler cannot warn you, and the failure shows up at runtime.
The file uses declare module "name" { ... }. That form only works in a file that has no top-level import or export, since otherwise the file is a module and the statement becomes an augmentation. Inside the block, export function is enough. You do not repeat declare.
Functions that also carry properties
Many JavaScript libraries export a function with extra fields attached. Declare the function and merge a namespace with the same name:
declare function slugify(text: string): string;
declare function slugify(text: string[]): string[];
declare namespace slugify {
const version: string;
}
const slug = slugify("Hello World"); // string
const v = slugify.version; // stringThe overloads and the version field describe a single value.
Declaring a variable instead of a function
Sometimes the global is a variable whose type is an overloaded interface. Use declare const with the type from the earlier sections:
interface Formatter {
(value: number): string;
(value: Date, locale: string): string;
}
declare const format: Formatter;
const s1 = format(3);
const s2 = format(new Date(), "en-US");Pick declare function when the thing is a function declaration in the JavaScript, and declare const plus an interface when the thing is built another way or needs extra members. Both give the same call behavior.
Merging interfaces adds overloads, and merge order matters
Interfaces with the same name in the same scope merge. If both declare call signatures or methods with the same name, the result is one overloaded set. The ordering rule is the one that surprises people: later declarations come first.
interface Matcher {
(input: unknown): string;
}
interface Matcher {
(input: number): number;
}
declare const match: Matcher;
const r = match(5); // numberThe merged signature list is (input: number): number followed by (input: unknown): string. Order within one declaration block is kept. The block that comes later in the program goes ahead of earlier blocks. If you wrote the number signature in the first interface and unknown in the second, the broad one would be tried first and swallow every call.
There is one exception. A signature whose parameter has a string literal type is moved to the front of the merged list, regardless of declaration order. This is why you can add a narrow event name or tag name to a library interface and be sure it is found first.
Adding an overload to a built-in interface
You can use this to extend the standard library types. This example teaches document.createElement about a custom element. It needs the dom library in your tsconfig.json:
interface XWidget extends HTMLElement {
open(): void;
}
declare global {
interface Document {
createElement(tagName: "x-widget"): XWidget;
}
}
const widget = document.createElement("x-widget");
widget.open();
export {};export {} makes the file a module, and declare global is how a module reaches the global scope. The literal-string signature goes ahead of the existing createElement overloads, so "x-widget" resolves to XWidget while "div" still resolves to HTMLDivElement.
Which form to use
| Situation | Form | Implementation needed? |
|---|---|---|
| You write the function body and want overloads | Function declaration with overload signatures | Yes, one implementation signature |
| The value is an arrow function or object member | Interface or alias with call signatures, then assign | Yes, one function that is assignable to every signature |
| You compose overloads from existing function types | Intersection of function types | No, only the type |
| The code lives in JavaScript or another package | `declare function` or `declare module` in a `.d.ts` file | No, the body exists elsewhere |
| You want to add an overload to a library interface | Interface merging in `declare global` or an augmentation | No |
Pitfalls specific to type-level overloads
- Inference sees only the last signature.
ReturnType,Parameters, and anyinfer-based helper read the final overload. If you pass an overloaded function to a generic function that infers from its type, it will behave as if only the last overload existed. - Ambient overloads cannot be verified. A
.d.tsfile is a promise, not a check. Wrong signatures compile cleanly and fail when the code runs. Test declaration files with a small file of example calls, including calls that must not compile. - The order is part of the contract. In a single list, order decides which signature is chosen. In merged interfaces, later blocks come first, except for string-literal signatures. Do not rely on file order across a large project. Put related signatures together.
- A broad signature early shadows a narrow one.
(x: unknown): unknownin front of(x: string): stringmeans the string version is never selected. Place the general signature last, as you do in a function declaration. - Method and property syntax differ in strictness. Under
strictFunctionTypes, parameters of a function-typed property are compared strictly, while parameters of a method are compared bivariantly. For overloaded members, the method form (get(key: string): string) is the usual choice because it follows the same rules as classes and library typings. - A union is often enough. If no return type changes with the argument, one signature with a union parameter describes the same function and avoids all of the above. Earlier chapters covered this trade-off, and it applies equally when you write a type for a callback.
Worked exercise: typing an arrow function with two shapes
Here is a small helper that returns a lookup function. The lookup can be called with an index or with a predicate, as the Registry.get method did earlier. This time it is a standalone function type:
interface Lookup {
(index: number): string | undefined;
(predicate: (item: string) => boolean): string | undefined;
}
function makeLookup(items: string[]): Lookup {
function lookup(index: number): string | undefined;
function lookup(predicate: (item: string) => boolean): string | undefined;
function lookup(
arg: number | ((item: string) => boolean)
): string | undefined {
return typeof arg === "number" ? items[arg] : items.find(arg);
}
return lookup;
}
const find = makeLookup(["a", "b", "c"]);
const second = find(1); // "b"
const match2 = find((item) => item === "c"); // "c"Here the overloads live in a nested function declaration, which is checked as usual, and the interface lets the rest of your code use the result without caring how it was built. Notice that (item) => item === "c" has its parameter inferred: once the compiler selects the predicate overload, the callback gets its contextual type from that overload.
Exercise
You have interface Parser { (input: string): number; (input: string[]): number[]; }. Why does const p: Parser = (input: string | string[]) => typeof input === "string" ? Number(input) : input.map(Number); fail to compile, and how do you fix it while keeping the compiler's checks?
Show answer
The arrow function has one signature that returns number | number[]. For the first signature in Parser, the return type must be assignable to number, and for the second it must be assignable to number[]. The union is assignable to neither, so the assignment is an error. Write a function declaration with two overload signatures and one implementation signature, then assign the function to Parser. The implementation signature check allows the broad return type, and the overloads match the interface exactly.
Exercise
Two files declare interface Matcher. The first has (input: unknown): string; and the second has (input: number): number;. What does match(5) return for a declare const match: Matcher, and why?
Show answer
It returns number. When interfaces merge, signatures from later declarations are placed before signatures from earlier ones, so (input: number): number is tried first and matches the argument 5. If the order were reversed, the unknown signature would match first and the result would be string.
Exercise
Given declare function parse(input: string): number; declare function parse(input: string[]): number[];, what is ReturnType<typeof parse> and why? What would you change to make it number?
Show answer
It is number[], because inference from an overloaded function type uses only the last signature. To make it number, move the string overload to the end of the list. Otherwise, define the type you need directly, for example type One = number, instead of deriving it from an overloaded function.
Exercise
A .d.ts file declares export function parse(input: string): string[][]; export function parse(input: string, withHeader: boolean): string[][] | Record<string, string>[]; export function parse(input: string, withHeader: true): Record<string, string>[];. What goes wrong for the call parse(text, true), and how do you fix the file?
Show answer
The boolean signature comes before the true signature and accepts the literal true, so it matches first. The call returns the union instead of Record<string, string>[]. Fix it by putting the withHeader: true signature before the withHeader: boolean signature, so the specific signature is tried first and the general one acts as a fallback.