How do you mark a function parameter as optional, and what type does it implicitly get?
Short answer
Add a '?' after the parameter name; TypeScript automatically adds 'undefined' to its type, and optional parameters must come after all required parameters in the parameter list.
Advertisement
AModel answer
Add a '?' after the parameter name; TypeScript automatically adds 'undefined' to its type, and optional parameters must come after all required parameters in the parameter list.
function greet(name: string, title?: string) {
return title ? `${title} ${name}` : name;
}
greet('Sam'); // 'Sam'
greet('Sam', 'Dr.'); // 'Dr. Sam'Real-world example
Making a configuration parameter optional so callers can omit it and rely on default in-function behavior.
Likely follow-ups
- Can an optional parameter come before a required parameter in the list?
Related topics