Codectionary / Developer documentation / TypeScript

Correlated Function Overloads

Overload signatures describe different accepted call shapes and their return types while sharing one implementation. The implementation signature must support all overloads, but is not an extra public call signature. Use overloads when a simple union signature cannot express a useful argument-to-result relationship.

Syntax

function convert(value: string): number;
function convert(value: number): string;

Examples

Correlated Function Overloads: working example

Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints 13, then 12.

function convert(value: string): number;
function convert(value: number): string;
function convert(value: string | number): number | string {
  return typeof value === "string" ? Number(value) : String(value);
}
console.log(convert("12") + 1);
console.log(convert(12).toUpperCase());
  1. Expected result: The program prints 13, then 12.
  2. A string argument selects a number return type.
  3. A number argument selects a string return type even though the shared implementation uses a union.

Best practices

  • Prefer a union parameter when all cases have the same return type.
  • Check conversion validity where Number can produce NaN.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading