← Back to TypeScript Course | Chapter 3: Variables and Functions | Lesson 6 of 10

Optional Parameters

Optional parameters allow a function to be called without providing every parameter. In TypeScript, an optional parameter is marked with a question mark.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
function search(term: string, caseSensitive?: boolean) {
  console.log(`Searching for "${term}"`, caseSensitive ? "(case sensitive)" : "");
}
search("typescript");

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.