Optional Parameters

What

Optional parameters are function arguments that do not need to be provided when the function is called.

How

You mark a parameter as optional by adding a question mark (?) after its name in the function signature:

function greet(name: string, title?: string): string {
  if (title) {
    return `Hello, ${title} ${name}!`;
  }
  return `Hello, ${name}!`;
}

greet("Gandalf");           // Valid
greet("Gandalf", "Wizard"); // Valid

Why

Optional parameters allow you to build flexible functions that can handle varying amounts of data. In TypeScript, an optional parameter automatically includes undefined in its type (e.g., string | undefined), forcing you to handle the case where the value is missing.

Summary

Optional parameters must always come after required parameters to avoid ambiguity during function calls.