BeCuriouzLearn something new every day
Optional, Default & Rest Parameters
💡 Use ? for skippable params, = value for fallbacks, and ...rest (optionally tuple-typed) to gather a flexible or exact set of trailing arguments.
Recall from the last card that TypeScript checks how many arguments you pass. Sometimes you want flexibility — and TypeScript gives you three tools for that.
An optional parameter is marked with ? after its name, letting callers skip it. Inside the function its type includes undefined, so you must handle that case. A default parameter goes further: = value supplies a fallback when the argument is missing, and TypeScript infers the type from that default.
function greet(name: string, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
greet("Ada"); // "Hello, Ada!"
greet("Ada", "Hi"); // "Hi, Ada!"
function log(msg: string, prefix?: string) {
return prefix ? `[${prefix}] ${msg}` : msg; // prefix is string | undefined
}A rest parameter collects any number of trailing arguments into an array using .... It must come last. Typed as number[] it accepts any count of numbers — but you can also give it a tuple type to demand an exact shape and order:
function sum(...nums: number[]) {
return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6
function move(...args: [x: number, y: number]) {
return args; // exactly two numbers required
}
move(3, 4); // ok — move(3) is a type errorKey rule: an optional parameter can't sit before a required one, and a default already makes a parameter effectively optional — so you never write both ? and = on the same parameter.