Sub topic 3
Optional, Default, and Rest Parameters
Assume you already know basic JavaScript functions, callbacks, primitive and object types, arrays, and union types. You should also be able to run TypeScript with tsc or inspect errors in an editor.
Function parameters can be required, optional, given default values, or collected into a rest parameter. These choices describe which calls are valid and what type the function receives.
Optional parameters
Add ? after a parameter name to make it optional:
function buildName(first: string, last?: string): string {
return last ? `${first} ${last}` : first;
}
buildName("Ada");
buildName("Ada", "Lovelace");
// buildName(); // error: first is requiredAn optional parameter has the type string | undefined inside the function. The function must handle the case where the caller leaves it out. A truthiness check works here because an empty last name is treated as absent. Use an explicit check when empty strings are meaningful:
function formatLabel(label?: string): string {
return label === undefined ? "Unnamed" : label;
}All required parameters must come before optional parameters. This would be invalid because the caller could not clearly provide the second argument:
// function invalid(first?: string, last: string): string {
// return `${first} ${last}`;
// }Default parameters
A default parameter supplies a value when the caller passes undefined or omits the argument:
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}`;
}
greet("Ada"); // "Hello, Ada"
greet("Ada", "Good morning");
greet("Ada", undefined); // also uses "Hello"A parameter with a default value is optional at the call site. Inside the function, TypeScript treats greeting as a string, because the default guarantees a value.
The default expression runs when the function is called, not when it is defined:
function createId(prefix: string = "item"): string {
return `${prefix}-${Date.now()}`;
}Use a default when one sensible value can replace a missing argument. Use an optional parameter when the function needs to distinguish “not supplied” from a normal value.
Rest parameters
A rest parameter collects zero or more remaining arguments into an array. It must be the final parameter, and its type must be an array or tuple:
function sum(...nums: number[]): number {
return nums.reduce((total, n) => total + n, 0);
}
sum(); // 0
sum(2, 3, 5); // 10
// sum(2, "3"); // errorYou can combine required parameters with a rest parameter:
function logMessage(level: string, ...messages: string[]): void {
console.log(`[${level}]`, ...messages);
}
logMessage("info", "Connected", "User loaded");The rest variable is a new array inside the function. It does not change the caller's arguments.
| Parameter form | Call-site behavior | Type inside the function | Column |
|---|---|---|---|
| `value: string` | Must be supplied | `string` | |
| `value?: string` | May be omitted | `string \ | undefined` |
| `value: string = "x"` | May be omitted | `string` | |
| `...values: string[]` | Zero or more values | `string[]` |
Choosing the parameter form
Use a required parameter when the function cannot work without a value. Use ? when absence is meaningful and must be handled. Use a default when a standard replacement makes the function simpler. Use rest when callers may provide an arbitrary number of values.
Exercise
Write a function named joinWords that accepts a required separator and any number of words, then returns the words joined by that separator.
Show answer
function joinWords(separator: string, ...words: string[]): string { return words.join(separator); }