Skip to content

Optional Parameters

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.

function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}!`;
}
greet("Alice"); // "Hello, Alice!" -- greeting is undefined
greet("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 parameter
function createUser(options: { name: string; age?: number }) {
return { name: options.name, age: options.age ?? 0 };
}
createUser({ name: "Alice" }); // age defaults to 0

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 parameter
function greet(greeting?: string, name: string) { ... }
// Fix: put optional/default parameters last
function greet(name: string, greeting?: string) { ... }
  1. Inside a function, what type does an optional parameter greeting?: string actually have?

    Answerstring | undefined β€” you must handle the possibility that it wasn't passed.
  2. What’s the difference between greeting?: string and greeting: string = "Hello"?

    AnswerThe optional parameter can be undefined inside the function if omitted; the default parameter automatically substitutes the given fallback value, so it's never undefined inside the function body.
  3. Why can’t a required parameter come after an optional one in the parameter list?

    AnswerBecause 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.