Function overloads

Intermediate · 10 min

Giving one function several call signatures so its return type can follow its arguments, and knowing when a union or optional parameter is the simpler answer.

Before thisFunction type expressions and call signaturesUnion and literal types

Andrew Burgess · 10 min

Function overloads

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Andrew BurgessReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Overloads exist for functions whose return type depends on which arguments were passed; a single signature with union parameters and a union return loses that link, and callers get the wide type every time.
  • An overloaded function is a list of overload signatures (no bodies) followed by one implementation signature with the body; callers only ever see the overload signatures.
  • The implementation signature must be general enough to accept every overload's parameters and return every overload's result, which usually means unions or optional parameters.
  • TypeScript checks a call against the overloads from top to bottom and uses the first one that matches, so the more specific signatures belong first.
  • The body is only checked against the implementation signature, so it can return the wrong type for a particular overload without any error; keeping overloaded bodies small and obvious is the defence.
  • A call whose argument is a union of two overloads' parameter types matches neither overload, which is why a single signature with a union parameter is preferable whenever the return type doesn't need to vary.
  • Several call signatures in one object type or interface, or several method declarations in a class, are the same mechanism in a different place.

When the output depends on the input

Some JavaScript functions behave differently depending on what you hand them. Pass parse a single string and you get a number back; pass it an array of strings and you get an array of numbers. At runtime that’s perfectly clear. The type system, given one signature, can only describe it loosely:

function parseLoose(input: string | string[]): number | number[] {
  return Array.isArray(input) ? input.map(Number) : Number(input);
}

const n = parseLoose("42"); // number | number[]
n.toFixed(2); // Error: Property 'toFixed' does not exist on type 'number | number[]'.

The caller passed a string and knows a number comes back, but the type says otherwise, so every call site has to narrow a value whose shape was never in doubt. The signature has lost the link between “which input” and “which output.” Overloads restore it.

Overload signatures and the implementation

An overloaded function is a stack of signatures without bodies, followed by one implementation:

function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]): number | number[] {
  return Array.isArray(input) ? input.map(Number) : Number(input);
}

const one = parse("42"); // number
const many = parse(["1", "2"]); // number[]
one.toFixed(2); // fine

The first two lines are overload signatures. They’re the public face of the function: each one is a way callers are allowed to call it, with its own return type. The third is the implementation signature, and it’s for the body only. Callers can’t see it. Hover over parse and the editor shows “+1 overload,” not the union version.

Think of a help desk with separate windows for separate requests. Each window has a sign saying what you bring and what you leave with. Behind the counter, one clerk handles all of them. Customers only read the signs; the clerk has to be able to handle every window’s request.

That’s the compatibility rule. The implementation must accept every overload’s parameters and be able to return every overload’s result, which is why its types are usually unions. If one overload took a boolean the implementation doesn’t accept, TypeScript would report “This overload signature is not compatible with its implementation signature.”

Overloads by argument count

Overloads also fit functions whose arguments mean different things depending on how many there are:

function range(end: number): number[];
function range(start: number, end: number): number[];
function range(a: number, b?: number): number[] {
  const [start, end] = b === undefined ? [0, a] : [a, b];
  return Array.from({ length: Math.max(end - start, 0) }, (_, i) => start + i);
}

range(5); // [0, 1, 2, 3, 4]
range(2, 5); // [2, 3, 4]

The return type doesn’t change here, so the main gain is documentation: the editor shows callers two clean signatures with meaningful names, end alone or start and end, instead of an a and an optional b.

How calls are resolved

For each call, TypeScript tries the overloads from top to bottom and takes the first that fits. Two consequences follow.

Order matters. Put specific signatures first. A broad overload near the top swallows calls meant for the narrower ones below it.

Unions don’t spread across overloads. Each overload is tried on its own, so an argument typed as a union of two overloads’ parameters matches neither:

function len(s: string): number;
function len(arr: unknown[]): number;
function len(x: string | unknown[]) {
  return x.length;
}

const value = Math.random() > 0.5 ? "hi" : [1, 2];
len(value); // Error: No overload matches this call.

Both overloads return number anyway, so these overloads add nothing. A single function len(x: string | unknown[]): number is simpler and accepts that call. The TypeScript handbook’s advice is worth following: prefer a union parameter over overloads whenever the return type doesn’t need to vary.

What the compiler doesn’t check

One gap to know about. The body is checked against the implementation signature only. If parse mistakenly returned [Number(input)] for a string, it would still compile, because number[] is a valid return under the implementation’s number | number[]. TypeScript verifies that the overloads are compatible with the implementation, not that each branch keeps each overload’s promise. Keep overloaded bodies small, and test them.

Overloads outside function declarations

The same idea appears wherever call signatures do. An object type or interface can list several call signatures, and a class can declare a method several times before its implementation:

interface Formatter {
  (value: number): string;
  (value: Date): string;
}

class Store {
  get(key: "count"): number;
  get(key: "name"): string;
  get(key: string): number | string {
    return key === "count" ? 0 : "";
  }
}

The class version is common in library typings, such as the DOM’s document.createElement returning a different element type for each tag name. Later in the roadmap, generics and conditional types offer another route to “return type follows input,” often with fewer signatures.

About the video

Andrew Burgess’s video, titled “I was wrong,” is about exactly the judgement this lesson ends on. He covers the basic syntax, the rules the implementation signature has to follow, and then a realistic maybe example and a larger widget-update example where overloads give callers more accurate types than a union could. Watch it after the sections above; the examples make most sense once the overload/implementation split is clear. The two links below cover the same feature with different examples if you want more practice reading overload stacks.

Check yourself

  1. 01A function `parse(input: string | string[]): number | number[]` works fine at runtime. What problem would overloads solve for its callers?

    With the single signature, `parse("42")` is typed `number | number[]` even though it always returns a `number`, so every caller has to narrow a result whose shape they already know. Overloads for `string` returning `number` and `string[]` returning `number[]` let TypeScript pick the precise return type from the argument.

  2. 02Why can't callers use the implementation signature of an overloaded function directly?

    Once overload signatures are declared, the implementation signature is hidden from callers; it only exists to type the body. It is usually deliberately wide, with unions or optional parameters, and exposing it would allow combinations of arguments none of the overloads permit.

  3. 03Given overloads `len(s: string): number` and `len(arr: unknown[]): number`, why does `len(Math.random() > 0.5 ? "hi" : [1, 2])` fail?

    TypeScript resolves a call against one overload at a time. The argument's type is the union `"hi" | number[]`, which isn't assignable to `string` alone or to `unknown[]` alone, so no single overload matches. Since both overloads return `number`, the better design is one signature taking `string | unknown[]`.

  4. 04Your overloads say `parse(input: string): number`, but the body accidentally returns an array when given a string. Will TypeScript catch it?

    No. The body is checked only against the implementation signature, which allows returning `number | number[]` for any input. The compiler confirms each overload is compatible with the implementation, not that each code path honours its specific overload. That is a reason to keep overload bodies short and to test them.

  5. 05Why should more specific overloads be listed before more general ones?

    Overload resolution picks the first signature that accepts the arguments. If a general signature, say one taking `unknown`, comes first, it matches every call and the specific signatures below it are never used, so callers get the general return type.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark