Default & Rest Parameters

`param = default` and `...args: T[]`

Default & Rest Parameters

Default values let parameters be omitted. Rest parameters collect remaining arguments into a typed array.

3 min read Level 1/5 #typescript#defaults#rest
What you'll learn
  • Use default values
  • Use rest parameters
  • Recognize the type inference for both

Two parameter modifiers — defaults and rest.

Default Values

function greet(name: string, punctuation = "!") {
  return `Hi ${name}${punctuation}`;
}

greet("Ada");          // "Hi Ada!"
greet("Ada", "?");     // "Hi Ada?"

The default value gives TS the type. Here punctuation is inferred as string. Adding an explicit annotation is optional:

function greet(name: string, punctuation: string = "!") { ... }

Defaults Are Like Optional

A parameter with a default is automatically optional — callers can omit it. You don’t need ?: AND =.

Where Defaults Live

Defaults are evaluated at call time, not at function-definition time:

let nextId = 1;
function id(value: number = nextId++) {
  return value;
}

id();   // 1
id();   // 2

(Be careful with this pattern — usually defaults should be constants.)

Rest Parameters

function sum(...nums: number[]): number {
  return nums.reduce((s, n) => s + n, 0);
}

sum(1, 2, 3);          // 6
sum(1, 2, 3, 4, 5);    // 15
sum();                  // 0

...nums: number[] collects all remaining arguments into a number[]. Always the LAST parameter.

Rest With Other Parameters

function format(prefix: string, ...parts: string[]): string {
  return `${prefix}: ${parts.join(", ")}`;
}

format("User", "Ada", "admin");   // "User: Ada, admin"

The rest parameter comes after fixed ones.

Spreading Into a Function

The reverse direction — call a function with an array of args:

const args: [string, number] = ["Ada", 36];
function greet(name: string, age: number) { /* ... */ }
greet(...args);   // ✓ tuple spreads correctly

For TS to typecheck the spread, the source needs to be a tuple (or a typed array matching the rest parameter).

Up Next

Overloads — when one function should accept multiple signatures.

Overloads →