Optional and Default Parameters
Make parameters optional with ? or give them default values.
Syntax
function f(a: number, b = 10) { }Add ? after a parameter name to make it optional β callers can leave it out. Inside the function its type includes undefined.
Alternatively, give a parameter a default value with =. If the caller omits it, the default is used instead.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- A logging function makes the log level optional so callers can omit it when the default 'info' level is sufficient.
- A utility function defaults a separator to ',' so callers only need to pass it when they want a custom delimiter.
- A UI component rendering function makes a className parameter optional to avoid forced empty string arguments.
More examples
Optional parameter with ?
Marks level as optional (string | undefined) and applies a default with the nullish coalescing operator.
function log(message: string, level?: string): void {
const lvl = level ?? 'info';
console.log(`[${lvl.toUpperCase()}] ${message}`);
}
log('Server started'); // uses default
log('Disk full', 'error'); // uses provided levelDefault parameter value
Uses a default parameter value so the separator is automatically string-typed and pre-filled when omitted.
function join(items: string[], separator: string = ', '): string {
return items.join(separator);
}
console.log(join(['a', 'b', 'c'])); // 'a, b, c'
console.log(join(['a', 'b', 'c'], ' | ')); // 'a | b | c'Optional and default combined
Combines a literal-union default parameter with an optional boolean, showing both patterns in one realistic signature.
function createButton(
label: string,
type: 'button' | 'submit' | 'reset' = 'button',
disabled?: boolean
): string {
const dis = disabled ? ' disabled' : '';
return `<button type="${type}"${dis}>${label}</button>`;
}
Discussion