Skip to main content

Optional Parameters

Marking a parameter optional

Add ? after the parameter name. The caller may then pass it or leave it out; inside the function its type becomes T | undefined.

function greet(name: string, greeting?: string) {
// greeting is string | undefined here
return `${greeting ?? "Hello"}, ${name}`;
}

greet("Ajay"); // Valid: "Hello, Ajay"
greet("Ajay", "Welcome"); // Valid: "Welcome, Ajay"

Optional parameters must come last

Everything after an optional parameter must also be optional — otherwise the compiler can't tell which argument is which.

function f(a: string, b?: number, c: boolean) {} // Error: required 'c' after optional 'b'
function f(a: string, b: boolean, c?: number) {} // Valid: optional last

Optional ? vs a default value

A default value also makes a parameter optional, and removes the undefined from its type:

function greet(name: string, greeting = "Hello") {
// greeting is just string here — never undefined
return `${greeting}, ${name}`;
}

Use ? when "missing" is meaningful and you'll handle undefined. Use a default when there's a sensible fallback — it's cleaner and keeps the type narrow (string, not string | undefined).