Optional Parameters
In this page:
Basic Optional Parameters
Placing a ? right after a parameter name, like (age?: number), marks that parameter optional, meaning callers can leave it out entirely. Inside the function, that parameter's type automatically includes undefined to reflect that it might not have been provided.
Example: Basic Optional Parameters
function greet(name: string, age?: number) {
console.log(name, age);
}
greet("Meera");
Optional Numbers
Optional numeric parameters are useful when a function has a sensible default behavior but also supports an extra numeric setting, like an optional precision or limit. Callers who don't need that level of control can simply omit it.
Example: Optional Numbers
function roundValue(value: number, precision?: number) {
return precision === undefined ? Math.round(value) : Number(value.toFixed(precision));
}
console.log(roundValue(3.14159), roundValue(3.14159, 2));
Checking Optional Values
Because an optional parameter may be undefined, it should be checked before it's used in an operation that requires a concrete value, such as arithmetic or a method call. TypeScript's control-flow analysis narrows the type away from undefined once that check is in place.
Example: Checking Optional Values
function printAge(age?: number) {
if (age !== undefined) {
console.log(age + 1);
} else {
console.log("Age not provided");
}
}
printAge();
Required Before Optional
Required parameters must always come before optional ones in a function's parameter list, since TypeScript needs to know unambiguously which arguments correspond to which parameters. You can't have an optional parameter followed by a required one.
Example: Required Before Optional
function createUser(name: string, age?: number) {
console.log(name, age);
}
// function bad(age?: number, name: string) {} // rejected: optional before required
createUser("Yusuf");
When to Use Optional Parameters
Optional parameters shine when a function covers one common, simple use case by default but also supports extra configuration for less common scenarios. This keeps the common call site short while still allowing more detailed calls when needed.
Example: When to Use Optional Parameters
function search(term: string, caseSensitive?: boolean) {
console.log(`Searching for "${term}"`, caseSensitive ? "(case sensitive)" : "");
}
search("typescript");
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: