Optional, default, and rest parameters
Typing parameters callers may leave out, parameters with fallback values, and functions that take any number of arguments.
Parameter and return typesArrays and tuplesNull, undefined, and strict null checks
Optional, default, and rest parameters
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- TypeScript checks argument count as well as argument types, so a call that leaves out a parameter is an error unless that parameter is marked optional, given a default, or collected by a rest parameter.
- An optional parameter `x?: T` can be left out by callers and has type `T | undefined` inside the body, so the body has to deal with the `undefined` case before using it.
- A default parameter `x = 10` is optional to callers but plain `number` inside the body, and its type is inferred from the default value, so it usually needs no annotation.
- Optional parameters must come after required ones; a default placed before a required parameter is allowed, but callers then have to pass `undefined` explicitly to trigger it.
- `x?: T` and `x: T | undefined` are different: the first lets callers omit the argument, the second makes them pass something, even if that something is `undefined`.
- A rest parameter `...items: T[]` collects the remaining arguments into an array, must come last, and must be typed as an array or tuple type.
- Spreading an array into a function with a fixed number of parameters only type-checks if TypeScript knows the array's length, which means it has to be a tuple, for example via `as const`.
JavaScript doesn’t count your arguments. TypeScript does.
Call a JavaScript function with fewer arguments than it declares and nothing complains; the missing ones are just undefined. Call it with more and the extras are ignored. That flexibility is how a lot of real APIs work — toFixed() with or without a digit count, console.log with any number of values — but it also means a forgotten argument slips through until something breaks.
TypeScript closes that gap by checking the number of arguments as well as their types:
function greet(name: string, title: string) {
return `Hello, ${title} ${name}`;
}
greet("Ada"); // Error: Expected 2 arguments, but got 1.
That’s the right default. But when a function genuinely does accept a variable number of arguments, you need a way to say so. TypeScript gives you three, and each describes a different situation.
Optional parameters: “you may leave this out”
Put a ? after the parameter name and callers are allowed to omit it:
function greet(name: string, title?: string) {
if (title) {
return `Hello, ${title.toUpperCase()} ${name}`;
}
return `Hello, ${name}`;
}
greet("Ada");
greet("Ada", "Dr.");
The other half of that deal shows up inside the body. If callers can leave title out, then title might be undefined, so its type there is string | undefined. Call title.toUpperCase() without the if check and strict stops you. The ? doesn’t hide the missing case; it makes you handle it.
Optional parameters have to come after all the required ones. If title were first, a call with one argument would be ambiguous.
A related form looks similar but means something different:
function search(query: string, limit: number | undefined) {
return limit === undefined ? query : `${query} (top ${limit})`;
}
search("ts", undefined); // fine
search("ts"); // Error: Expected 2 arguments, but got 1.
Here limit can hold undefined, but it’s still required. Callers must write something in that slot. Use ? when leaving the argument out is normal; use T | undefined when you want every caller to make an explicit choice.
Default parameters: “if you leave this out, use this”
Often “optional” really means “optional, with a sensible fallback.” That’s what a default value expresses:
function fetchWithRetry(url: string, retries = 3) {
for (let attempt = 1; attempt <= retries; attempt++) {
console.log(`GET ${url}, attempt ${attempt}`);
}
}
fetchWithRetry("/api/users");
fetchWithRetry("/api/users", 5);
fetchWithRetry("/api/users", undefined); // also uses 3
Three things are worth noticing. retries needs no annotation, because its type is inferred from the default, so it’s number. To callers it is optional, just like retries?: number. Inside the body it is plain number, never undefined, because the default fills any gap. That last point is why a default is often nicer than a ?: there’s no narrowing to do.
Passing undefined explicitly triggers the default, which is a JavaScript rule TypeScript simply models. It also explains an odd case: a default placed before a required parameter is legal, but then the only way to use the default is to pass undefined in that position. Keep defaulted parameters at the end.
Rest parameters: “any number of these”
When a function takes a list of values of open-ended length, collect them with a rest parameter. The runtime behavior is plain JavaScript — the leftover arguments arrive as an array — and the type annotation describes that array:
function average(label: string, ...scores: number[]) {
const sum = scores.reduce((total, s) => total + s, 0);
return `${label}: ${scores.length ? sum / scores.length : 0}`;
}
average("Week 1");
average("Week 1", 80, 92, 75);
average("Week 1", 80, "92"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
The rules are short. A rest parameter must be last, there can only be one, and its type must be an array or a tuple. Write ...scores: number and TypeScript tells you a rest parameter must be of an array type, because at runtime it always is one.
A tuple type lets a rest parameter describe a fixed, ordered sequence instead of a homogeneous list:
function logEntry(...entry: [level: "info" | "warn", message: string]) {
const [level, message] = entry;
console.log(`[${level}] ${message}`);
}
logEntry("warn", "disk almost full");
Spreading arrays into calls
The reverse direction — spreading an array into a call — has one surprise:
const loose = [8, 5];
Math.atan2(...loose); // Error: A spread argument must either have a tuple type or be passed to a rest parameter.
const pair = [8, 5] as const;
Math.atan2(...pair); // fine
loose is number[], which could hold any number of elements, while Math.atan2 wants exactly two. TypeScript won’t guess. Declaring the array as const makes it a readonly tuple of length two, and the call checks. Spreading into a rest parameter, like average("x", ...loose), is always fine, since a rest parameter accepts any length.
About the video
Dave Gray’s video is a 32-minute chapter of a longer course, and the embed starts at 15:28, where “Optional Parameters” begins. From there it runs through “Default Parameters” (18:10) and “Function with Rest Params” (21:39), and you can stop at 25:21, where it moves on to the never type, which belongs to other lessons. He builds each example in the editor, including why an optional parameter has to come after the required ones, which pairs well with the rules above. The text here adds the T | undefined distinction and the tuple cases for rest and spread, which the video doesn’t dwell on. If you want the first fifteen minutes too, they cover function type aliases, which the next lesson handles in detail.
Check yourself
Inside `function greet(name: string, title?: string)`, why is `title.toUpperCase()` an error under `strict`?
Because `title?` means the caller may leave it out, so inside the body its type is `string | undefined`. Calling a method on a possibly-undefined value is exactly what `strictNullChecks` exists to catch. You need to narrow first, for example with `if (title)` or `title?.toUpperCase()`, or give it a default instead.
What is the type of `retries` inside `function fetchWithRetry(url: string, retries = 3)`, and what can callers do with it?
Inside the body it is `number`, inferred from the default `3`, and never `undefined` because the default fills the gap. Callers may omit it, pass a number, or pass `undefined` explicitly, which also triggers the default. Passing a string is an error.
What is the practical difference between declaring a parameter as `limit?: number` and as `limit: number | undefined`?
With `limit?: number`, callers can simply leave the argument out. With `limit: number | undefined`, the parameter is still required, so callers must write something in that position, even if it is `undefined`. The body sees `number | undefined` in both cases; the difference is entirely on the calling side.
Why does `const pair = [8, 5]; Math.atan2(...pair);` fail, and how do you fix it?
`pair` is inferred as `number[]`, an array of unknown length, while `Math.atan2` takes exactly two parameters. TypeScript can't prove the spread supplies exactly two values, so it reports that a spread argument must have a tuple type. Declaring `const pair = [8, 5] as const` makes it a fixed-length tuple and the call type-checks.
Why must a rest parameter be typed as an array (or tuple) and not as a single element type?
At runtime a rest parameter is always an array of whatever arguments were left over, possibly empty. The annotation describes that array, so `...scores: number[]` is correct and `...scores: number` is rejected with 'A rest parameter must be of an array type'.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.