The contract at every call
A function's signature is a contract between the person who wrote it and everyone who calls it: give me these arguments, and I will give you back this. In JavaScript the contract lives in documentation and in people's heads, and nothing enforces it; the JavaScript course's lesson on functions listed the consequences (missing arguments become undefined, extra ones are ignored, nobody notices). In TypeScript the contract is written in the signature and checked at every call site, and when the contract changes, every caller that no longer fits is reported.
You already know the basics from earlier lessons. This one fills in the details that come up in real code: optional and destructured parameters, function types for callbacks, the surprising rules for void, overloads for functions whose return type depends on their arguments, and the typing of this.
Parameters, return types and function types
// Typing functions: parameters, return types, optional, default and rest parameters.
function bmi(weightKg: number, heightM: number): number {
return weightKg / heightM ** 2;
}
// Optional (?) and default parameters. A default also gives the parameter its type.
function greet(name: string, title?: string, punctuation = "!"): string {
return `Hello, ${title ? title + " " : ""}${name}${punctuation}`;
}
// Rest parameters are typed as arrays.
function joinPath(...segments: string[]): string {
return segments.map((s) => s.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
}
// Destructured parameters: the type annotation goes after the whole pattern.
interface ChartOptions {
title: string;
width?: number;
height?: number;
}
function describeChart({ title, width = 640, height = 480 }: ChartOptions): string {
return `${title} (${width}x${height})`;
}
// Function types: for variables and parameters that hold functions.
type BinaryOp = (a: number, b: number) => number;
const ops: Record<string, BinaryOp> = {
add: (a, b) => a + b, // a and b are numbers: contextual typing
pow: (a, b) => a ** b,
};
// A callback whose result is ignored is typed as returning void.
function repeat(times: number, action: (i: number) => void): void {
for (let i = 0; i < times; i++) action(i);
}
console.log(bmi(70, 1.75).toFixed(1));
console.log(greet("Okafor"), greet("Okafor", "Dr."), greet("Okafor", undefined, "?"));
console.log(joinPath("/api/", "v2", "", "/users/"));
console.log(describeChart({ title: "Rainfall" }), describeChart({ title: "Wind", height: 200 }));
console.log(ops.add(2, 3), ops.pow(2, 10));
const collected: number[] = [];
repeat(3, (i) => collected.push(i * i)); // push returns a number; void callbacks may return anything
console.log(collected);
export {};22.9
Hello, Okafor! Hello, Dr. Okafor! Hello, Okafor?
api/v2/users
Rainfall (640x480) Wind (640x200)
5 1024
[ 0, 1, 4 ]What each part shows:
- Parameters always need types, unless the function is a callback whose type is known from context. Under
--strict, a parameter without one is an error (noImplicitAny), never a silentany. - Return types can usually be inferred. Here they are written for documentation. A good rule: write them on exported functions, which form your module's public contract, so that a change inside the function that accidentally changes its return type is caught at the function rather than at some distant caller. Inferred return types can surprise you:
function half(n: number) { return n > 0 ? n / 2 : "negative"; }is inferred as returningnumber | "negative", which is legal and probably not what anyone meant. title?: stringis optional, so inside the function its type isstring | undefined.punctuation = "!"has a default, so it is optional for callers and its type,string, is inferred from the default. Passingundefinedexplicitly uses the default, as the third call shows. Optional parameters must come after required ones; otherwise the compiler saysA required parameter cannot follow an optional parameter.- Rest parameters are typed as arrays:
...segments: string[]. - Destructured parameters take one annotation for the whole pattern, after it:
{ title, width = 640, height = 480 }: ChartOptions. Combined with an interface, this is the TypeScript form of the options-object idiom: callers name what they pass, the compiler checks every name, and defaults are visible in the signature. - Function types look like arrow functions:
(a: number, b: number) => number. Inops, the arrows' parameters need no annotations, because theRecord<string, BinaryOp>gives them a contextual type.
void callbacks
repeat declares its callback as (i: number) => void, yet the program passes (i) => collected.push(i * i), which returns a number (push returns the new length). This is allowed on purpose. A void return type in a function type means "the caller will ignore the result", not "the function must return nothing", so that common one-line arrows like this one, or items.forEach((x) => list.push(x)), type-check. By contrast, a function declaration with an explicit : void return type may not return a value. The distinction exists for convenience, and it is the kind of rule that is easier to remember once you have seen why.
How function types are compared
When is one function type assignable to another? A function that takes fewer parameters can stand in for one that takes more (JavaScript ignores extra arguments, so a callback that doesn't need the index can leave it out), and parameter types are compared in the "opposite" direction to return types: a function that accepts any Animal can be used where a function accepting a Dog is expected, but not the other way round. Under --strict, the option strictFunctionTypes enforces this for function types; for compatibility with older code, method signatures are checked more loosely, as lesson three mentioned. Most of the time you will never think about this, but it explains the occasional error about a callback "not being assignable" when its parameter is more specific than the slot it is passed into.
Overloads
Definition— function overloads
Overloads give a function several call signatures, each listed as a declaration without a body, followed by one implementation signature with the body. Callers see only the overload signatures, tried in order; the implementation must be compatible with all of them, but is not callable directly.
// Overloads: several call signatures, one implementation.
function formatDate(date: Date): string;
function formatDate(dates: Date[]): string[];
function formatDate(input: Date | Date[]): string | string[] {
const one = (d: Date) => d.toISOString().slice(0, 10);
return Array.isArray(input) ? input.map(one) : one(input);
}
const launch = new Date(Date.UTC(2026, 6, 8));
const single = formatDate(launch); // string
const many = formatDate([launch, new Date(0)]); // string[]
console.log(single.toUpperCase(), many.length, many[1]);
// Overloads keyed by a literal argument: the return type depends on the value passed.
interface Circle { kind: "circle"; radius: number }
interface Square { kind: "square"; side: number }
function make(kind: "circle", size: number): Circle;
function make(kind: "square", size: number): Square;
function make(kind: "circle" | "square", size: number): Circle | Square {
return kind === "circle" ? { kind, radius: size } : { kind, side: size };
}
const c = make("circle", 2); // Circle: c.radius is allowed
const s = make("square", 3); // Square: s.side is allowed
console.log(c.radius, s.side);
// Often a union parameter is simpler than overloads, when the return type doesn't vary.
function lengthOf(x: string | unknown[]): number {
return x.length;
}
console.log(lengthOf("añil"), lengthOf([1, 2, 3]));
export {};2026-07-08 2 1970-01-01
2 3
4 3formatDate returns a string for one date and a string[] for several, and the overloads tell each caller precisely which, so single.toUpperCase() and many.length both type-check without any narrowing. make goes further: the value of the first argument picks the overload, so make("circle", 2) is known to return a Circle. The DOM's types give document.createElement the same kind of precision (using a generic signature, next lesson's subject, rather than a list of overloads): createElement("canvas") returns an HTMLCanvasElement, while createElement("input") returns an HTMLInputElement.
Overloads have costs. The implementation is checked against its own loose signature (Date | Date[] in, string | string[] out), not against each overload, so it can return the wrong kind for a given input without complaint. And a caller holding a value that might be either kind is stuck, because no single overload accepts the union:
function formatDate(date: Date): string;
function formatDate(dates: Date[]): string[];
function formatDate(input: Date | Date[]): string | string[] {
return Array.isArray(input) ? input.map(String) : String(input);
}
declare const either: Date | Date[];
formatDate(either);main.ts(8,12): error TS2769: No overload matches this call.
Overload 1 of 2, '(date: Date): string', gave the following error.
Argument of type 'Date | Date[]' is not assignable to parameter of type 'Date'.
Type 'Date[]' is missing the following properties from type 'Date': toDateString, toTimeString, toLocaleDateString, toLocaleTimeString, and 38 more.
Overload 2 of 2, '(dates: Date[]): string[]', gave the following error.
Argument of type 'Date | Date[]' is not assignable to parameter of type 'Date[]'.
Type 'Date' is missing the following properties from type 'Date[]': length, pop, push, concat, and 35 more.The long message is worth learning to read: TypeScript tried each overload in turn and explains why each one failed. The guidance most teams follow: if the return type doesn't depend on the arguments, use a union parameter (like lengthOf) instead of overloads; use overloads when it does, and list the most specific signatures first, because the first match wins. Lesson eight shows a third option, a generic function with a conditional return type, which can express some of these relationships in a single signature.
Callable objects, this and async functions
// Call signatures, functions with properties, `this` parameters and async functions.
interface Counter {
(): number; // it can be called...
count: number; // ...and it has a property
reset(): void;
}
function makeCounter(): Counter {
const counter = (() => ++counter.count) as Counter;
counter.count = 0;
counter.reset = () => {
counter.count = 0;
};
return counter;
}
const next = makeCounter();
next();
next();
console.log(next(), next.count);
next.reset();
console.log(next.count);
// A `this` parameter declares what `this` must be; it is erased from the JavaScript.
interface Thermostat {
celsius: number;
}
function toFahrenheit(this: Thermostat): number {
return this.celsius * 9 / 5 + 32;
}
const kitchen = { celsius: 21, toFahrenheit };
console.log(kitchen.toFahrenheit().toFixed(1));
// Async functions return Promise<T>; await unwraps T.
async function fetchTemperature(city: string): Promise<number> {
await new Promise((resolve) => setTimeout(resolve, 5));
return city.length * 3; // a stand-in for a real request
}
async function main(): Promise<void> {
const temps = await Promise.all(["Lusaka", "Riga"].map(fetchTemperature));
console.log(temps); // number[]
}
main();
export {};3 3
0
69.8
[ 18, 12 ]- Call signatures. In JavaScript a function is an object and can carry properties. An interface with a bare
(): numbermember describes something callable; addingcountandresetdescribes the rest. Theas Counterassertion is needed because the properties are attached after the arrow is created; this is one of the few places an assertion is the honest tool, and it is contained insidemakeCounter. thisparameters. A first parameter namedthisis not a real parameter: it declares the typethismust have, and it is erased from the JavaScript. CallingtoFahrenheitas a method of an object with acelsiusfield works; calling it plainly is caught. Recall from the JavaScript course that a plain call leavesthisundefined in strict mode, and here the compiler says so:The 'this' context of type 'void' is not assignable to method's 'this' of type 'Thermostat'. This is how TypeScript catches the "lostthis" bug when a function needs one.- Async functions always return a
Promise, and the return type says what it resolves to:Promise<number>. Inside,return city.length * 3returns a plain number; theasynckeyword wraps it.awaitunwraps the type again, andPromise.allover an array ofPromise<number>givesnumber[]. Notemain()at the end rather than top-levelawait: this course's checker compiles each program as a CommonJS module, where top-levelawaitisn't allowed; in an ES module project you would simplyawait.
Where function types run out
Try to type the once helper from the JavaScript course, which wraps any function so that it runs only the first time. With what you know so far, the honest signature is something like function once(fn: (...args: any[]) => any): (...args: any[]) => any. It compiles, and it throws away everything: wrap a function that takes a string and returns a number, and the wrapper accepts anything and returns any, so the very first misuse slips through and the any spreads to everything computed from the result.
What the signature needs to say is "whatever kind of function you give me, I return a function of the same kind". That is a relationship between the input type and the output type, and expressing such relationships is exactly what generics, the subject of the next lesson, are for. The same gap appears in every higher-order function: memoize, debounce, retry, map over your own containers. Keep the problem in mind; its solution is one of the most satisfying parts of TypeScript.
How professionals type functions
- Annotate the boundaries, infer the inside. Exported functions get explicit parameter and return types; local helpers and callbacks usually don't need return types at all.
- Keep parameters few. More than three positional parameters, or any boolean flag, suggests an options object with an interface. Literal unions beat booleans:
sort(list, "descending")oversort(list, false). - Make illegal calls impossible. If two options must be given together, or never together, encode that in the parameter type (a union of option shapes) rather than checking at run time.
- Prefer
readonlyarray parameters (items: readonly Item[]) for functions that only read, so callers know their data is safe and the function can't mutate by accident. - Don't over-overload. Two or three overloads that express a real dependency between input and output are useful; ten are a sign that the function does too many things. Split it.
- Write documentation comments. A
/** ... */comment directly above a function, with@paramand@returnstags if you like (the TSDoc convention), is shown by every editor when someone hovers over a call. Types say what goes in and out; the comment says why and what for: units, valid ranges, what happens at the edges.@deprecatedin such a comment makes editors strike through every use of the function, a gentle way to migrate callers. - Arrow or declaration, annotate the same way.
const toKm = (miles: number): number => miles * 1.609;puts the return type after the parameter list, just like a declaration. Alternatively, give the variable a function type,const toKm: (miles: number) => number = (miles) => miles * 1.609;, which is common when a function must fit a type defined elsewhere, such as an event handler's. - Be honest about failure. A function that can fail on ordinary input returns
T | undefinedor aResult; a function that throws should say so in its documentation comment (/** @throws ... */), because TypeScript has no checked exceptions.
Common misconceptions
Misconception
"An optional parameter and a parameter with a default are the same." For callers they are: both can be left out. Inside the function, an optional parameter has type T | undefined and must be checked, while a parameter with a default always has type T.
Misconception
"A callback typed as returning void must not return anything." In a function type, void means the result is ignored, so callbacks that happen to return values are accepted. Only a function declared with an explicit : void return type is forbidden from returning a value.
Misconception
"The implementation signature of an overloaded function can be called." It is hidden. Callers see only the overload signatures, which is why a union argument that matches no single overload is rejected even though the implementation would accept it.
Misconception
"TypeScript checks which exceptions a function throws." It doesn't: there are no checked exceptions, and a catch variable is unknown. Errors that callers are expected to handle belong in the return type.
Exercises
As before, answer type questions as the compiler would print them.
1. Typing functions
Warm-upComputationalUsing the lesson's greet(name: string, title?: string, punctuation = "!"), what does this print?
console.log(greet("Mbali", "", "."), greet("Mbali", "Prof."));
2. Typing functions
CoreComputationalWhat return type does TypeScript infer for this function? Write it as the compiler prints it.
function half(n: number) {
return n > 0 ? n / 2 : "negative";
}
3. Typing functions
CoreHumanrepeat(times: number, action: (i: number) => void) is called as repeat(3, (i) => collected.push(i)), and push returns a number. Why does this compile?
4. Typing functions
CoreComputationalWith the lesson's overloads make(kind: "circle", size: number): Circle and make(kind: "square", size: number): Square, which line compiles?
5. Typing functions
CoreComputationalWhat does this print?
interface Counter {
(): number;
count: number;
}
function makeCounter(step: number): Counter {
const counter = (() => (counter.count += step)) as Counter;
counter.count = 0;
return counter;
}
const byTwo = makeCounter(2);
const byFive = makeCounter(5);
byTwo();
byFive();
console.log(byTwo(), byFive.count, byTwo.count);
export {};
6. Typing functions
Warm-upComputationalWhy is function label(prefix?: string, id: number): string { ... } rejected?
7. Typing functions
StretchComputationalGiven function toFahrenheit(this: { celsius: number }): number { return this.celsius * 9 / 5 + 32; }, which call compiles?
Further reading and resources
- TypeScript Handbook: More on functions · MicrosoftFunction types, call signatures, overloads, this and void, in depth.
- TypeScript Handbook: Type compatibility (comparing two functions) · Microsoft
- TSConfig reference: strictFunctionTypes · Microsoft