Optional Parameters
Optional Parameters
Section titled βOptional ParametersβWhat it means
Section titled βWhat it meansβTypeScript lets you mark a function parameter optional with ?, meaning callers can omit it (its type becomes T | undefined inside the function). A default parameter (= value) is related but different β it supplies a fallback value when the argument is omitted, and TypeScript infers the parameter type from the defaultβs type if not otherwise annotated.
Examples
Section titled βExamplesβfunction greet(name: string, greeting?: string): string { return `${greeting ?? "Hello"}, ${name}!`;}greet("Alice"); // "Hello, Alice!" -- greeting is undefinedgreet("Alice", "Hi"); // "Hi, Alice!"
function greetWithDefault(name: string, greeting: string = "Hello"): string { return `${greeting}, ${name}!`;}greetWithDefault("Bob"); // "Hello, Bob!" -- default kicks in
// Optional properties on an object parameterfunction createUser(options: { name: string; age?: number }) { return { name: options.name, age: options.age ?? 0 };}createUser({ name: "Alice" }); // age defaults to 0Common mistake
Section titled βCommon mistakeβPutting a required parameter after an optional (or default) parameter β TypeScript disallows this ordering, because thereβd be no way for a caller to skip the optional one and still supply the required one positionally.
// Error: A required parameter cannot follow an optional parameterfunction greet(greeting?: string, name: string) { ... }
// Fix: put optional/default parameters lastfunction greet(name: string, greeting?: string) { ... }Quick practice
Section titled βQuick practiceβ-
Inside a function, what type does an optional parameter
greeting?: stringactually have?Answer
string | undefinedβ you must handle the possibility that it wasn't passed. -
Whatβs the difference between
greeting?: stringandgreeting: string = "Hello"?Answer
The optional parameter can beundefinedinside the function if omitted; the default parameter automatically substitutes the given fallback value, so it's neverundefinedinside the function body. -
Why canβt a required parameter come after an optional one in the parameter list?
Answer
Because parameters are matched positionally β if you could skip an earlier optional parameter, there'd be no unambiguous way to tell TypeScript which argument belongs to which required parameter.