Typescript Foundations / Functions

Rest Parameter

πŸ‘‰ Rest parameters let you represent an indefinite number of arguments as an array.

function func(...args: type[]) {}

βœ… Basic Example

function sum(...numbers: number[]): number {
  return numbers.reduce((total, num) => total + num, 0);
}

sum(1, 2, 3);         // 6
sum(10, 20, 30, 40);  // 100

🧠 numbers: number[] β†’ TypeScript infers the rest parameter is an array of numbers.


βš™οΈ Mixed Parameters + Rest

function greet(greeting: string, ...names: string[]) {
  return `${greeting}, ${names.join(" & ")}`;
}

greet("Hello", "Alice", "Bob"); // "Hello, Alice & Bob"

πŸ”₯ Important:

βœ… Rest parameter must come last in the parameter list.

function invalid(...nums: number[], prefix: string) {} // ❌ Error


βœ… Parameter Ordering Rules in TypeScript

πŸ” Correct order:

required β†’ default β†’ optional β†’ rest

But since optional and default parameters can technically swap, the main rule is:

Rest parameter must always come last β€” that's non-negotiable!


πŸ”₯ So the safe and clean order is:

function example(
  required: string,
  defaultParam: number = 10,
  optionalParam?: boolean,
  ...rest: string[]
) {
  // function body
}

βœ… This works perfectly:

example("req");                       // defaultParam = 10, optionalParam = undefined, rest = []
example("req", 20);                   // optionalParam = undefined
example("req", 20, true, "a", "b");   // rest = ["a", "b"]

✨ Summary

Feature

Purpose

Example

...

Handle multiple args as an array

function f(...args: string[])

Type

Must be an array type

...nums: number[]

Must be last

Only one rest param allowed

f(a: string, ...rest: number[])


βœ… Real-World Use Cases

  • Summing or combining many values

  • Forwarding arguments to other functions

  • Building custom utility functions