Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 96 ยท Functions

Function Overloads

Learn TypeScript function overloads - overload and implementation signatures, ordering rules, when overloads beat union types, and generic alternatives with type maps.

Some functions behave differently depending on what you pass them. A function might accept either a single date or a start and end date, or return a number when asked for 'number' and a boolean when asked for 'boolean'. A single signature with union types can describe the inputs, but it loses the link between a particular input and its particular output.

Function overloads solve this. You write several overload signatures, each describing one valid way to call the function, followed by one implementation that handles all of them. Callers see only the overloads, so each call gets the precise return type for its arguments. This lesson shows how overloads work, the rules that trip people up, and when a simpler union or a generic function is the better tool.

Overload signatures and the implementation

An overloaded function is a list of signatures without bodies, followed by one function with a body:

TypeScript A function with two overloads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The two overloads say: you may call formatDuration with one number, or with two dates. The implementation's parameters are wide enough for both cases (number | Date, and an optional second Date), and the body tells them apart with typeof.

The end! non-null assertion from Type Assertions and the Non-Null Operator is acceptable here: inside the implementation, TypeScript doesn't connect "first is a Date" to "end was passed," but the overloads guarantee it.

Callers only see the overloads

The implementation signature is not callable from outside. Even though it would technically accept formatDuration(new Date()) (one date, no end), no overload allows that, so it's rejected. This example fails on purpose:

TypeScript Calls that match no overload (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Both calls fail:

TEXT
main.ts(8,16): error TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.
main.ts(9,16): error TS2345: Argument of type 'number' is not assignable to parameter of type 'Date'.

Each call has an argument count that fits exactly one overload (one argument for the first, two for the second), so TypeScript reports the problem against that overload. When several overloads could apply, you'll see error TS2769, "No overload matches this call," followed by the error from the last overload it tried.

That's exactly the protection you want: the type system enforces the valid combinations, not just the valid individual types. With a single signature (first: number | Date, end?: Date), both bad calls would have compiled.

Return types that depend on arguments

The biggest win from overloads is a return type that changes with the input. A common pattern is a string literal argument that selects the result type:

TypeScript Return types chosen by a literal argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each call gets an exact type, so port + 1 is arithmetic, hosts.map is an array method, and no checks or assertions are needed. With a single signature returning number | boolean | string[], every caller would have to narrow the result first.

The implementation's return type must be compatible with every overload's return type, which usually means it's the union of them. TypeScript doesn't check that the 'number' branch really returns a number for the 'number' overload; inside the body you only have the implementation signature. Overloads describe the contract to callers, and you're responsible for keeping the body honest.

The rules of overloading

A handful of rules cover nearly every overload error you'll meet.

1. The implementation must be compatible with each overload. Every overload's parameters must be assignable to the implementation's parameters, and the implementation's return type must fit each overload's return type. If not, you get error TS2394, "This overload signature is not compatible with its implementation signature." Typical causes are a parameter type you forgot to add to the implementation's union, or a parameter that's required in the implementation but missing from an overload (make it optional).

2. Overloads must be adjacent and share modifiers. All signatures and the implementation sit next to each other, with the same name, and either all exported or none.

3. TypeScript picks the first overload that matches, top to bottom. It does not look for the "best" match. So put more specific overloads first and general ones last. Here the order is wrong. This example fails on purpose:

TypeScript A general overload hides a specific one (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error is main.ts(11,13): error TS18048: 'n' is possibly 'undefined'. The string 'hello' matches the first overload (unknown accepts everything), so n gets the type number | undefined, and the more precise second overload is never used. Swap the two overloads and the call resolves to number:

TypeScript Specific overloads first

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

4. A union argument doesn't match separate overloads. If you have parseValue(text, 'number') and parseValue(text, 'boolean') overloads, a call with a variable of type 'number' | 'boolean' fails with TS2769, because no single overload accepts the whole union. Add an overload that takes the union (and returns the union) if callers need it.

Overloads vs union types

Overloads are powerful, but they add lines and maintenance. If the return type is the same no matter which input you pass, a union parameter says the same thing more simply:

TypeScript
// Unnecessary: both overloads return number.
function countChars(value: string): number;
function countChars(value: string[]): number;
function countChars(value: string | string[]): number {
  return typeof value === 'string' ? value.length : value.join('').length;
}

// Better: one signature.
function countChars2(value: string | string[]): number {
  return typeof value === 'string' ? value.length : value.join('').length;
}

The union version is also easier to call: a caller holding a string | string[] can pass it straight in, which the overloaded version rejects (rule 4). Use this rule of thumb:

  • Same return type for every input: use a union (or optional parameters).
  • Different valid argument combinations (one number or two dates): overloads.
  • Return type depends on the input: overloads, or a generic signature as shown next.

A generic alternative: type maps

When the result type follows from a key argument, a generic function with a lookup type often replaces a long list of overloads. Describe the mapping once in an interface, and let the type parameter pick the entry:

TypeScript A generic signature instead of overloads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This version has several advantages over overloads: adding a new kind means adding one line to ParsedTypes and one parser; the body is fully type-checked (each parser must really return the mapped type); and union keys just work. The syntax uses tools from later chapters: keyof and indexed access ParsedTypes[K] from keyof, typeof and Indexed Access Types, the { [K in keyof ...]: ... } mapped type from Mapped Types, and constraints from Generic Constraints and Defaults. Conditional types (Conditional Types) are another way to compute a return type from an argument type.

Overloads in methods, interfaces and arrow functions

Class methods are overloaded the same way: list the signatures, then the implementation, all inside the class. Interfaces and object types describe overloads with several call signatures or several declarations of the same method:

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

interface Cache {
  get(key: string): string | undefined;
  get(key: string, fallback: string): string;
}

Arrow functions and function expressions can't have overload lists themselves. To give one an overloaded type, declare a type with multiple call signatures, like Formatter above, and annotate the variable with it. Because TypeScript can't check an arrow's single body against several signatures, that usually needs an assertion, which is one more reason function declarations are the natural home for overloads.

Overloads also appear constantly in declaration files: many built-in and library functions you call every day (String.prototype.replace, Array.prototype.reduce, Node's fs.readFileSync) are typed with overloads. When your editor shows "+2 overloads" on hover, this is what it means.

One quirk to know: type-level tools such as ReturnType<typeof fn> and Parameters<typeof fn> (see Built-in Utility Types) only look at the last overload of an overloaded function. That's another reason to put the most general overload last: it's the one these utilities will report.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given overloads f(x: string): string and f(x: number): number, and an implementation f(x: string | number): string | number, does f(true as unknown as string | number) compile?

    Callers only see the overload signatures. Neither one accepts string | number on its own, so the call fails unless you add an overload for the union.
  2. 2. Overloads are listed as g(x: unknown): unknown first and g(x: string): string second. What is the type of g('hi')?

    TypeScript uses the first overload that matches. unknown accepts a string, so the second, more specific overload is never reached. Put specific overloads first.
  3. 3. What does error TS2394 mean?

    The implementation must accept every overload's parameters and return a type compatible with each overload's return type. Widen the implementation's parameter types or return type to fix it.
  4. 4. A function returns number whether it gets a string or a string[]. What is the best way to type it?

    When the return type does not depend on the input, a union parameter is simpler than overloads and also accepts callers who hold a string | string[] value.
  5. 5. Why is the generic type-map version of parseValue often better than a list of overloads?

    With overloads, the body only sees the implementation signature and nothing checks each branch. A type map ties each key to its result type, accepts union keys and is easy to extend.

Summary

  • An overloaded function has several overload signatures (no body) followed by one implementation; callers see only the overloads.
  • Overloads express valid argument combinations and return types that depend on the arguments.
  • The implementation must be compatible with every overload (otherwise TS2394), and calls that match no overload fail with TS2769.
  • TypeScript picks the first matching overload, so order them from most specific to most general.
  • A union argument doesn't match a set of separate overloads; prefer a single union signature when the return type doesn't change.
  • Generic functions with a type map (ParsedTypes[K]) or conditional types are often a cleaner, fully checked alternative.

Next: this, Parameter Destructuring and Type Predicates