Optional and Default Parameters
Prerequisites: Functions with types
A parameter followed by ? is optional — callers may omit it, and
its type automatically includes undefined. A default value makes a
parameter optional too, while giving it a fallback.
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}!`;
}
function greetWithDefault(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
Common mistakes
- Putting a required parameter after an optional one — TypeScript requires optional/default parameters to come last.