Sub topic 1
The Problem: One Function, Several Call Shapes
Prerequisites
Assume you know basic TypeScript types, unions, literal types, functions, type narrowing, classes, and interfaces.
The problem: one function, several call shapes
A function can accept different kinds of arguments and return a different type for each kind. A single union-typed signature describes the inputs, but often loses the connection between an input and its result.
function toArray(value: string | number): (string | number)[] {
return [value];
}
const result = toArray("x");
// result is (string | number)[], not string[]The implementation always returns an array, but callers know that a string produces a string[] and a number produces a number[]. Function overloads express those separate call shapes.
Writing overload signatures
An overload signature is a function declaration without a body. Each signature gives callers a supported argument and return type. Put all overload signatures before the implementation signature.
function toArray(value: string): string[];
function toArray(value: number): number[];
function toArray(value: string | number): (string | number)[] {
return [value];
}
const words = toArray("x"); // string[]
const numbers = toArray(1); // number[]The compiler checks a call against the overload signatures. It does not use the implementation signature as an additional public option.
The implementation signature and why callers cannot see it
The implementation signature describes the values that the function body must handle. Its parameters and return type must be broad enough to support every overload. The body still needs normal narrowing.
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
return typeof value === "string"
? value.toUpperCase()
: value.toFixed(2);
}A union argument does not automatically match either overload:
declare const value: string | number;
// Error: No overload matches this call.
// format(value);Add an overload when callers should be allowed to pass the union:
function format(value: string | number): string;Exercise
Why does toArray("x") produce string[] when the implementation returns (string | number)[]?
Show answer
The caller matches the string overload signature, which declares the result as string[]; the implementation signature is hidden from callers.