Optional, Default, and Rest Parameters


Optional, Default, and Rest Parameters#
Functions often need to be flexible in how many arguments they accept. TypeScript provides three powerful features to handle this: optional parameters, default parameters, and rest parameters. These allow you to write versatile functions while keeping type safety intact.
Optional Parameters
Optional parameters let callers omit arguments. Mark a parameter optional by adding a ? after its name.
function greet(name?: string): string {
return `Hello, ${name ?? "Guest"}!`;
}
console.log(greet()); // Hello, Guest!
console.log(greet("Alice")); // Hello, Alice!Note: Optional parameters must come after all required parameters.
Default Parameters
Default parameters provide a fallback value if the argument is omitted or undefined.
function multiply(a: number, b: number = 1): number {
return a * b;
}
console.log(multiply(5)); // 5
console.log(multiply(5, 2)); // 10Default parameters are implicitly optional and can simplify your function logic.
Rest Parameters
Rest parameters collect all remaining arguments into an array.
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(4, 5)); // 9Rest parameters must be the last parameter in the function signature.
Combining Parameter Types
You can combine required, optional, default, and rest parameters:
function buildName(
firstName: string,
lastName?: string,
...titles: string[]
): string {
let fullName = firstName;
if (lastName) fullName += ` ${lastName}`;
if (titles.length) fullName += `, ${titles.join(" ")}`;
return fullName;
}
console.log(buildName("John")); // John
console.log(buildName("John", "Doe")); // John Doe
console.log(buildName("John", "Doe", "PhD", "Esq.")); // John Doe, PhD Esq.Best Practices
- Place required parameters first, then optional/default, then rest parameters.
- Use default parameters to avoid manual checks for
undefined. - Avoid mixing optional and default parameters in confusing ways.
- Document your function parameters clearly.
Tip: Use rest parameters to handle variable argument lists
cleanly instead of arguments object.
Common Pitfalls
- Placing optional parameters before required ones causes errors.
- Forgetting that rest parameters must be last.
- Using
undefinedexplicitly can override default parameters unintentionally.
Warning: Calling a function with undefined for a default
parameter will use the default value, but passing null will not.
Next Steps
Next, explore function overloading in TypeScript to define multiple function signatures for more complex behaviors.