TypeScript · Lesson 12 of 42
Optional, default and rest parameters in TypeScript
Make parameters optional with ?, give them default values, and collect extra arguments with rest parameters while keeping everything type checked.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will handle functions whose arguments are not all required: ones with sensible defaults, ones that can be skipped, and ones that accept any number of values. TypeScript checks each of these, and knowing the rules saves a lot of confusion.
Optional parameters
In JavaScript, you can call a function with fewer arguments than it declares. TypeScript is stricter: a parameter is required unless you say otherwise. Add ? after the name to mark it optional:
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}`;
}
console.log(greet("Asha"));
console.log(greet("Asha", "Welcome"));Hello, Asha
Welcome, AshaInside the function, an optional parameter has the type string | undefined, because the caller may have left it out. That is why the code above uses ??, which supplies a fallback when the left side is undefined or null. If you forget to handle it, the compiler reminds you:
function shout(text: string, suffix?: string): string {
return text.toUpperCase() + suffix.toUpperCase();
}example.ts(2,31): error TS18048: 'suffix' is possibly 'undefined'.Default values
A default value gives the parameter a value when the argument is missing. It makes the parameter optional for callers, and the compiler infers its type from the default, so no annotation is needed:
function repeat(text: string, times = 2): string {
return text.repeat(times);
}
console.log(repeat("ab"));
console.log(repeat("ab", 3));abab
abababHere times is a number, inferred from 2. If you pass the wrong type, the usual error appears:
function repeat(text: string, times = 2): string {
return text.repeat(times);
}
repeat("ab", "three");example.ts(5,14): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.Defaults are usually better than optional parameters when there is a natural default, because inside the function the value is never undefined.
The ordering rule
Required parameters must come before optional ones. Otherwise, a caller could not skip the optional one and still supply the required one that follows it:
function build(prefix?: string, name: string): string {
return (prefix ?? "") + name;
}example.ts(1,33): error TS1016: A required parameter cannot follow an optional parameter.A parameter with a default value is the exception: it may come before a required parameter, but callers must then pass undefined explicitly to use the default. That is awkward, so putting defaults last is clearer.
Rest parameters
A rest parameter gathers all remaining arguments into an array. It is written with three dots and must come last. Its type is an array type:
function sum(label: string, ...numbers: number[]): string {
const total = numbers.reduce((acc, n) => acc + n, 0);
return `${label}: ${total}`;
}
console.log(sum("Empty"));
console.log(sum("Small", 1, 2, 3));Empty: 0
Small: 6The compiler checks each extra argument against the element type, so one stray string is caught:
function sum(...numbers: number[]): number {
return numbers.reduce((acc, n) => acc + n, 0);
}
sum(1, 2, "3");example.ts(5,11): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.The opposite operation, the spread syntax, passes an array as separate arguments. TypeScript checks that too, and for fixed-length cases a tuple type tells it exactly how many values the array holds:
function distance(x: number, y: number): number {
return Math.hypot(x, y);
}
const point: [number, number] = [3, 4];
console.log(distance(...point));5If point were a plain number[], the compiler could not be sure it contained two numbers and would reject the spread. This is a good example of why tuples exist.
Choosing between them
- A default when there is a sensible fallback value.
- An optional parameter when absence has a meaning of its own that the function must handle.
- A rest parameter when callers may pass any number of similar values.
- An options object when there are many optional settings, which keeps calls readable.
Common mistakes
Forgetting that optional means possibly undefined. Handle that case before calling methods on the value.
Putting a required parameter after an optional one. The compiler rejects it. Reorder, or use defaults.
Passing an array where separate arguments are expected. Use the spread operator, and a tuple type when the length is fixed.
Using optional where a default would do. Defaults save you from checking for undefined inside the function.
Exercise
Write function join(separator = ", ", ...parts: string[]): string. Call it with no extra arguments, with some, and with a custom separator. Then write a volume function that takes three optional dimensions defaulting to 1, and call it with one, two and three arguments. Finally, use spread with a tuple to call a function with three number parameters.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.