Codectionary / Developer documentation / TypeScript

Typed Rest Parameters

A rest parameter gathers any remaining arguments into an array.

What it is and why to use it

A rest parameter gathers any remaining arguments into an array. Its annotation describes that array, not a single argument. It is useful for a small function that accepts a variable number of values while checking every supplied value’s type.

Common mistakes and limitations

A rest parameter must be last. number[] permits any number of numeric arguments, while a rest tuple can constrain the exact positions and count. Avoid unchecked any[] when the function expects known element types.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

function sum(...values: number[]): number;

Examples

Typed Rest Parameters

Standalone TypeScript 5.8+ example; expected output is explained below.

function total(label: string, ...values: number[]): string {
  return label + ": " + values.reduce((sum, value) => sum + value, 0);
}
console.log(total("Scores", 3, 4, 5));
console.log(total("Empty"));
  1. label is the first required argument and values collects the remaining numbers.
  2. reduce begins at zero, so even the empty rest array has a defined sum.
  3. Both calls return formatted strings. A string in one of the numeric argument positions would be a type error.
  4. Expected output: Scores: 12 Empty: 0

Best practices

  • A rest parameter must be last. number[] permits any number of numeric arguments, while a rest tuple can constrain the exact positions and count. Avoid unchecked any[] when the function expects known element types.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading