Optional, Default & Rest Parameters

Optional, Default & Rest Parameters in TypeScript: At the trade counter of a builders' merchant the counterhand works from a printed order pad -- a carbon-copy…

The Analogy: The Order Pad at a Builders' Merchant Trade Counter

At the trade counter of a builders' merchant the counterhand works from a printed order pad -- a carbon-copy book where each order is one ruled page of boxes. Some boxes are outlined in heavy black: the account number, the delivery date. Those must be filled in, and a page handed over with a blank account box is passed straight back across the counter before anything is priced. A completed page is a placed order, and each box on it is one piece of information the order carries -- which is exactly what a function call is, and exactly what its parameters are. The heavy-outlined boxes are the required parameters: leave one empty and the order will not go through.

Below the required boxes sit two gentler kinds. Some carry a pre-printed house standard in faint grey -- "Delivery: collection" -- and if the customer leaves that box blank the counterhand simply takes the printed standard; write something in and that overrides it. Those are the default parameters: omit them and the body uses the default, supply them and yours wins. Other boxes are plain and unmarked, "special instructions" and the like; leave one blank and the counterhand records nothing at all against it, an empty space that means "not given". Those are the optional parameters: skip one and the body sees undefined, with no house standard to fall back on.

At the very foot of the page is an open ruled panel headed "further items", and this is where an order stops being fixed-shape. However many extra lines the customer reels off -- ten metres of this, a box of those, two of the other -- they all go down in that one panel, and the counterhand totals whatever is written there. That is the rest parameter: an open-ended list of arguments gathered into a single array. And the pad's layout is not negotiable: the fixed boxes come first and the open panel is always last, with only ever one such panel, because a second open list halfway up the page would leave no way to tell where one ended and the next began.

The failure mode is the difference between a blank box and a box with a dash scrawled in it, and it trips people constantly. A default box left genuinely blank gets the house standard -- that is the whole point of the faint grey print. But a box with "0" or a dash or the word "none" written in is not blank; it is an explicit instruction, and the counterhand takes it literally, standard ignored. Write a dash in the carriage box meaning "I don't know" and you have not asked for the standard carriage -- you have ordered zero carriage, and the total comes out short. A default fills in only for a box left untouched, never for a box you deliberately wrote something into, and it certainly never rescues you from writing nonsense in on purpose.


Syntax or Core Structure

Three markers change how a parameter is supplied. A trailing ? makes it optional, so its type includes undefined. An = value gives it a default, so the body sees a clean type with no undefined. A leading ... makes it a rest parameter, which is always an array type and gathers however many trailing arguments are passed.

// src/basics.ts
// optional: the type includes undefined when omitted
function label(code: string, note?: string): string {
    return note ? code + " (" + note + ")" : code;
}

// default: the body sees a clean number, never undefined
function carriage(pence = 500): number {
    return pence;
}

// rest: always an array, and it may be empty
function totalQty(...qtys: number[]): number {
    return qtys.reduce((a, b) => a + b, 0);
}

console.log(label("PIPE"), label("ELBOW", "brass"));
console.log(carriage(), carriage(750));
console.log(totalQty(4, 10, 2), totalQty());

Output:

PIPE ELBOW (brass)
500 750
16 0

label takes an optional note: called with one argument the note is undefined and the guard returns the bare code, so label("PIPE") is "PIPE" and label("ELBOW", "brass") is "ELBOW (brass)". carriage has a default of 500, so carriage() fills it in and carriage(750) overrides it. totalQty gathers all its arguments into an array: totalQty(4, 10, 2) sums to 16, and totalQty() with no arguments gets an empty array, so reduce returns its seed 0. Three markers, three behaviours, and none of them changes how the function is written inside.


Technical Depth: The Three Kinds, Ordering, and Tuple Rests

The three markers overlap enough to confuse, the pad's layout rules are enforced by the compiler, a default fires on undefined but never on null, and a rest parameter can be a tuple that carries positional types.

Optional, default, and union-with-undefined

Three signatures look alike and behave differently. What separates them is whether the caller may omit the argument, whether passing undefined is allowed, and what type the body actually sees.

Parameter formCaller may omitBody sees
note?: stringyesa string or undefined
note = "x"yesa plain string
note: string or undefinednoa string or undefined

The first form is optional: omit it and the body must handle undefined. The second has a default: omit it and the body gets a clean string, because the default has already filled the gap. The third is a required union: the caller cannot leave it out at all -- they must pass a string or the literal undefined -- and the body still has to guard. The middle form is usually what you want, because it gives the caller freedom while keeping the body free of guards.

The pad's layout rules

Required boxes come before optional ones, and the open panel is last. The compiler enforces both, because a required parameter after an optional one has no unambiguous call, and two rest parameters would have no boundary between them.

// src/order.ts
// function bad(note?: string, code: string) {}
//   error: A required parameter cannot follow an optional parameter.

function place(code: string, note?: string): string {   // required first
    return note ? code + "/" + note : code;
}

function lines(account: string, ...items: string[]): number {   // rest last, only one
    return items.length;
}

console.log(place("PIPE"), place("PIPE", "brass"));
console.log(lines("TC-42", "pipe", "elbow", "flux"));

Output:

PIPE PIPE/brass
3

place puts the required code before the optional note, which is the legal order; the commented bad is refused because a required box cannot follow an optional one. lines takes a required account and then a single rest items, which gathers the three trailing strings so items.length is 3. You may have only one rest parameter and it must be last, exactly as the pad has one "further items" panel at its foot.

A default fires for undefined, never for null

This is the blank-box-versus-dash rule in code. A default fills in when the argument is missing or explicitly undefined, but null is a value you wrote in the box, so it stands.

// src/defaulting.ts
function carriage(pence = 500): number {
    return pence;
}

console.log(carriage());              // omitted: default fires
console.log(carriage(undefined));     // undefined: default still fires
console.log(carriage(0));             // explicit 0: stands, no default

Output:

500
500
0

Omitting the argument and passing undefined both trigger the default, giving 500 twice. Passing 0 is an explicit value, so it stands and prints 0 -- which is exactly why you must not write the default as pence || 500 inside the body: || treats 0 as falsy and would wrongly replace it with 500. A real default parameter, or ??, only steps in for undefined, so a genuine 0 survives.

A rest can be a tuple, and can forward a signature

A rest parameter is usually a plain array, but typed as a tuple it carries a fixed count and per-position types. And Parameters<F> as a rest is how a wrapper forwards another function's arguments without restating them.

// src/forward.ts
// a tuple rest: two required numbers and an optional third
function point(...coords: [x: number, y: number, z?: number]): number {
    const [x, y, z = 0] = coords;
    return x + y + z;
}

function traced<F extends (...args: number[]) => number>(fn: F) {
    return (...args: Parameters<F>): ReturnType<F> => fn(...args);
}

const tp = traced(point);

console.log(point(1, 2), point(1, 2, 3));
console.log(tp(4, 5, 6));

Output:

3 6
15

point uses a tuple rest, so it demands at least x and y and allows an optional z that defaults to 0 on destructuring: point(1, 2) is 3 and point(1, 2, 3) is 6. traced wraps any numeric function, forwarding its arguments as Parameters<F> and its result as ReturnType<F>, so tp has the same signature as point and tp(4, 5, 6) is 15. This tuple-rest-plus-Parameters pattern is how every typed wrapper, decorator, and middleware preserves the signature it wraps.


Real World Example: A Delivery Ticket Builder

The trade counter needs a routine that turns one order into a priced delivery ticket: a required account, a couple of terms that have house standards (carriage and the VAT rate), and an open list of line items. The terms belong in an options object with a default so callers can leave them at standard, and the line items are the rest parameter -- however many the customer reels off. The routine totals the goods, adds carriage, applies VAT, and prints a ticket whose columns line up whatever the codes and quantities are.

// src/ticket.ts
interface Item {
    code: string;
    qty: number;
    unit: number;   // pence each
}

interface Terms {
    carriage?: number;   // pence
    vatRate?: number;    // percent
}

function ticket(account: string, terms: Terms = {}, ...items: Item[]): string {
    const { carriage = 500, vatRate = 20 } = terms;
    const w0 = 7, w1 = 5;
    const pad = (t: string, n: number) => t + " ".repeat(Math.max(0, n - t.length));
    const lines: string[] = [];
    lines.push("account: " + account + ", items: " + items.length);
    lines.push(pad("CODE", w0) + pad("QTY", w1) + "LINE");
    let goods = 0;
    for (const it of items) {
        const line = it.qty * it.unit;
        goods += line;
        lines.push(pad(it.code, w0) + pad(String(it.qty), w1) + String(line));
    }
    const net = goods + carriage;
    const vat = Math.round(net * vatRate / 100);
    lines.push("goods: " + goods);
    lines.push("carriage: " + carriage);
    lines.push("vat: " + vat);
    lines.push("total: " + (net + vat));
    return lines.join("\n");
}

const order = ticket(
    "TC-42",
    {},
    { code: "PIPE", qty: 10, unit: 120 },
    { code: "ELBOW", qty: 4, unit: 55 },
    { code: "FLUX", qty: 2, unit: 315 }
);

console.log(order);

Output:

account: TC-42, items: 3
CODE   QTY  LINE
PIPE   10   1200
ELBOW  4    220
FLUX   2    630
goods: 2050
carriage: 500
vat: 510
total: 3060

The signature reads account: string, terms: Terms = {}, ...items: Item[]: one required box, an options object defaulted to {} so its own defaults can apply, and the open panel of line items last. The destructure { carriage = 500, vatRate = 20 } = terms pulls the two terms with their house standards in one place, so an empty {} yields 500 carriage and a 20 percent rate. Each item's line is qty * unit: pipe is 10 at 120 is 1200, elbow is 4 at 55 is 220, flux is 2 at 315 is 630, and the goods total is 2050.

The ticket then adds the 500 carriage for a net of 2550, takes VAT at 20 percent as 510, and prints a total of 3060. The LINE column sums straight back to the printed goods, and because every column is padded to a fixed width the table stays square whatever the codes and quantities are. The options-object-plus-rest shape lets a caller change the carriage or the rate without touching the item list, and add items without touching the terms.

The code has real limits, and the sharpest is a design wart the parameter order forces. Because a rest parameter must be last, the terms object sits before the items, so a caller who wants only the house standards still has to pass an explicit {} to reach the item list -- the very ticket("TC-42", {}, ...) in the example, where that {} reads like noise. The honest fix is to drop the rest parameter and carry the items inside the options object as an items: Item[] field, so the call becomes a single named object with no positional {} to explain. Two smaller points: an empty item list still produces a valid ticket that charges carriage on zero goods, which a real system should reject rather than price; and Math.round on the VAT is exact here only because 2550 at 20 percent lands on a whole penny -- a fractional rate would force a rounding policy that must match whatever the accounts system does, or the ticket and the ledger will disagree by a penny.


Common Mistakes

  1. Writing note?: string = "x". A default already makes a parameter optional, so combining the ? marker with a default is illegal. Pick one: the ? for "may be undefined in the body", or the default for "filled in when omitted".
  2. Putting a required parameter after an optional one. (note?: string, code: string) is refused because there is no unambiguous way to call it. Reorder so every required parameter comes before the first optional one.
  3. Using || for a default inside the body. const n = input || 500 turns a legitimate 0 into 500, because || treats 0 as falsy. Use a real default parameter or ??, both of which only step in for undefined.
  4. Expecting a default to fire for null. Defaults fill in for a missing or undefined argument only; null is a value you passed, so it stands and can produce NaN in arithmetic. Guard null explicitly if callers might send it.
  5. Reading arguments in an arrow function. Arrow functions have no arguments object, so the old variadic trick silently fails. Use a typed rest parameter, which is clearer and works everywhere.
  6. Typing a rest parameter as a scalar. A rest parameter is always a collection: write ...qtys: number[] or a tuple, never ...qtys: number, which the compiler rejects.
  7. Declaring more than one rest parameter. Only the last parameter may be a rest, and there can be exactly one, because two open-ended lists would have no boundary between them. Gather everything trailing into a single rest.
  8. Skipping a middle default by leaving a hole. With defaults that are not last, a caller must pass undefined to skip one, and a string of undefined arguments is unreadable. Put defaults last, or move the flexible ones into an options object.
  9. Sharing a mutable default object across calls. An object or array default written as (opts = {}) or (xs = []) is re-created fresh on each call, which is correct; assuming instead that one shared instance persists between calls -- as a hoisted constant default would -- leads to state bleeding from one call into the next.

Best Practices

  • Prefer a default over an optional when a sensible standard exists. A default removes an undefined from the body, so the code that follows works with a clean type and no guard.
  • Collapse three or more optional parameters into an options object. A single named object reads far better at the call site than a run of positional arguments, and callers can pass the fields in any order.
  • Default the options object itself with = {}. It lets callers omit the object entirely, and the field defaults inside the destructure still apply, so fn(url) and fn(url, { retries: 5 }) both work.
  • Destructure options with their defaults at the top. Pulling every field and its default in one { a = 1, b = 2 } = opts line puts all the standards in one visible place rather than scattering ?? through the body.
  • Use ?? rather than || for run-time fallbacks. ?? steps in only for null or undefined, so a valid 0 or empty string survives; || would wrongly discard them.
  • Type a rest parameter as a tuple when position carries meaning. A tuple rest gives each slot its own type and can mark a trailing slot optional, which a plain array cannot, so misuse is caught at the call.
  • Forward signatures with Parameters<F> and ReturnType<F>. When wrapping a function, take ...args: Parameters<F> and return ReturnType<F> so the wrapper tracks the original signature automatically and never drifts from it.
  • Keep the rest parameter last and singular by design. Order the fixed, required parameters first and let the open list trail, so the shape matches how the compiler and readers both expect to find it.

Practice Exercises

  1. A defaulted greeting. Write getGreeting(name: string, timeOfDay = "morning"): string that returns "Good morning, Ada", and call it both with and without the second argument to see the default fire.
  2. An average with a label. Write average(label: string, ...scores: number[]): string that returns the label with the mean of the scores, returning the label with 0 when no scores are passed, and confirm the empty-rest case works.
  3. An options refactor. Take createUser(name: string, admin = false, notify = true, locale = "en") and refactor it into createUser(name: string, options: CreateUserOptions = {}) with the three flags as optional fields, and show both the old and new call sites.
  4. A typed logging wrapper. Write withLog<F extends (...args: any[]) => any>(fn: F) that returns a function of the same signature using Parameters<F> and ReturnType<F>, forwarding the arguments unchanged, and prove that calling the wrapper with a wrong argument type is a compile error.