Sub topic 3
Optional, default and rest parameters
This chapter assumes you can write basic JavaScript functions, including arrow functions and callbacks. It also assumes you know primitives, arrays and union types in TypeScript, and that you can already annotate parameters and return types. It covers how TypeScript types the three ways a function can accept a variable number of arguments.
Why argument count is checked
JavaScript lets you call a function with any number of arguments. Missing ones become undefined and extra ones are ignored. TypeScript checks the count at compile time. A call with too few or too many arguments is an error unless the signature says otherwise.
function area(width: number, height: number): number {
return width * height;
}
// area(2); // error: Expected 2 arguments, but got 1.
// area(2, 3, 4); // error: Expected 2 arguments, but got 3.Optional, default and rest parameters are the three ways to loosen that rule. Each one changes both what callers may write and what type the parameter has inside the body.
Optional parameters
A ? after a parameter name makes it optional. Inside the body, its type is the annotated type plus undefined.
function buildName(first: string, last?: string): string {
return last !== undefined ? `${first} ${last}` : first;
}
buildName("Ada"); // "Ada"
buildName("Ada", "Lovelace"); // "Ada Lovelace"
buildName("Ada", undefined); // allowed: undefined is a valid value
// buildName("Ada", "Lovelace", "King"); // error: Expected 1-2 arguments, but got 3.Here last has the type string | undefined. You must narrow it before calling string methods on it. The call buildName("Ada", undefined) is legal because undefined is part of the parameter's type.
Optional parameters must come after all required ones. This signature is rejected:
// function bad(a?: number, b: number): number { return b; }
// error: A required parameter cannot follow an optional parameter.The reason is that a caller could not skip a and still supply b by position.
Default parameters
A default value makes a parameter optional and supplies a replacement when the argument is undefined.
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}`;
}
greet("Ada"); // "Hello, Ada"
greet("Ada", "Welcome"); // "Welcome, Ada"
greet("Ada", undefined); // "Hello, Ada"The annotation is optional. In greeting = "Hello" the compiler infers string from the default. Inside the body the type is plain string, with no undefined, because the default fills the gap. Callers see the parameter as optional, so hovering over greet shows (name: string, greeting?: string) => string.
How defaults behave at runtime
- The default expression runs on every call where the argument is
undefined. A default of[]creates a fresh array each time, so calls do not share state. - Only
undefinedtriggers the default. Passingnulldoes not, and with strict null checks on,nullis a type error unless the annotation allows it. - A default can use earlier parameters, as in
function box(w: number, h = w).
function addTag(tag: string, tags: string[] = []): string[] {
return [...tags, tag];
}
addTag("a"); // ["a"]
addTag("b"); // ["b"], not ["a", "b"]Defaults before required parameters
Unlike ?, a default parameter may come before a required one. Callers then have to pass undefined explicitly to get the default.
function pad(width = 2, value: number): string {
return String(value).padStart(width, "0");
}
pad(undefined, 5); // "05"
pad(4, 5); // "0005"The parameter's type for callers is number | undefined. This pattern works but is rarely worth it. Put defaulted parameters last when you can.
You cannot combine the two forms. greeting?: string = "Hello" is an error because a default already makes the parameter optional.
Rest parameters
A rest parameter collects all remaining arguments into an array. It is written with ... and must have an array type.
function sum(...nums: number[]): number {
return nums.reduce((total, n) => total + n, 0);
}
sum(); // 0
sum(1, 2, 3); // 6
const values = [4, 5, 6];
sum(...values); // 15
function log(level: "info" | "warn", ...parts: string[]): void {
console.log(`[${level}]`, parts.join(" "));
}A function has at most one rest parameter, and it must be last. A rest parameter typed number instead of number[] is an error ("A rest parameter must be of an array type").
Tuples as rest types
A rest parameter can also be a tuple. This gives a fixed list of arguments that can carry labels and optional elements, which is useful when you want one name for the whole argument list.
function request(...args: [url: string, retries?: number]): string {
const [url, retries = 3] = args;
return `${url} (${retries} retries)`;
}
request("/users"); // "/users (3 retries)"
request("/users", 5); // "/users (5 retries)"Callers see two ordinary parameters, url and retries. This is the form that Parameters<typeof fn> returns, which a later chapter uses.
Spreading into fixed parameters
Spreading an array works for a rest parameter. It does not work for fixed parameters, because the compiler cannot know how many elements the array holds.
function area(width: number, height: number): number {
return width * height;
}
const dims = [3, 4];
// area(...dims);
// error: A spread argument must either have a tuple type or be passed to a rest parameter.
const pair: [number, number] = [3, 4];
area(...pair); // 12A tuple type fixes the length, so the spread is accepted.
How a call resolves each parameter
The compiler decides what to do with each parameter by asking the questions in the diagram below. Required parameters without an argument are the only case that fails.
Ordering rules at a glance
| Kind | Syntax | Type inside the body | Where it may appear | Column |
|---|---|---|---|---|
| Required | `a: T` | `T` | Before optional parameters | |
| Optional | `a?: T` | `T \ | undefined` | After required parameters |
| Default | `a: T = v` | `T` | Anywhere, but callers must pass `undefined` to skip it before a required parameter | |
| Rest | `...a: T[]` | `T[]` | Last, and only one |
Optional parameters in function types
When you describe a function with a function type, you write the same markers without default values. Defaults belong to implementations, not to types.
type NameBuilder = (first: string, last?: string) => string;
type Summer = (...nums: number[]) => number;
const build: NameBuilder = buildName;
const total: Summer = sum;
// type Bad = (x: number = 1) => void;
// error: A parameter initializer is only allowed in a function or constructor implementation.The function greet from earlier is assignable to (name: string, greeting?: string) => string, since the default shows up as ? in its type.
Do not use `?` for callback parameters you always pass
Writing an optional parameter in a callback type tells implementers that the callback might be called without it. If your code always provides the value, make it required.
function forEachItem(
items: string[],
callback: (item: string, index?: number) => void
): void {
for (let i = 0; i < items.length; i++) {
callback(items[i], i);
}
}
// forEachItem(["a"], (item, index) => index.toFixed());
// error: 'index' is possibly 'undefined'.The callback is forced to handle a case that never occurs. Declare index: number instead. Callers can still pass a function that ignores index, because a function with fewer parameters is assignable to one with more.
Common errors
- Truthiness checks on optional values. Zero, empty strings and
falseget treated as missing. Use=== undefined. - Expecting
nullto trigger a default. Onlyundefineddoes. - Optional before required. The compiler rejects it. Reorder, or use a default and pass
undefined. - Spreading a plain array into fixed parameters. Use a tuple type, or change the function to take a rest parameter.
- Assuming
exactOptionalPropertyTypesaffects parameters. That compiler flag applies to object properties only. A?parameter always acceptsundefined.
Exercise
Write a function repeat that takes a required string text, an optional-by-default number times (default 2), and then any number of extra string suffixes. Why can't the suffixes be placed before times?
Show answer
function repeat(text: string, times: number = 2, ...suffixes: string[]): string { return text.repeat(times) + suffixes.join(""); } A rest parameter must be the last parameter, because it collects everything after the fixed parameters. A signature like (text, ...suffixes, times) is a compile error.
Exercise
Given function f(a: number, b = 10, c?: string) {}, what is the type of b and of c inside the body, and which of f(1), f(1, undefined, "x") and f(1, null) compile with strict null checks on?
Show answer
Inside the body b is number and c is string | undefined. f(1) and f(1, undefined, "x") compile. f(1, null) does not, because null is not assignable to number | undefined.