Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A rest parameter allows a variadic function to accept an indefinite number of arguments as a single array variable. In TypeScript, it is denoted by the rest syntax (...) preceding the parameter name in the function signature and must be explicitly typed as an array or a tuple to enforce type safety across the aggregated arguments.

Syntax and Type Annotation

To define a rest parameter, append ... to the parameter identifier, followed by an array type annotation (T[] or Array<T>).
function aggregateData(param1: string, ...restParams: number[]): void {
    // restParams is typed as number[]
}
If no type annotation is provided, TypeScript implicitly infers the type as any[], which compromises type safety unless noImplicitAny is enabled in the tsconfig.json, in which case it throws a compiler error.

Architectural Constraints

When implementing rest parameters in a function signature, the TypeScript compiler enforces the following structural rules:
  1. Terminal Positioning: The rest parameter must be the final parameter in the function declaration. Placing a standard parameter after a rest parameter results in a syntax error (A rest parameter must be last in a parameter list).
  2. Singularity: A function signature can contain a maximum of one rest parameter.
  3. Optionality: Rest parameters cannot be marked as optional using the ? modifier. An empty argument list simply results in the rest parameter resolving to an empty array ([]).
// Valid
function validSignature(a: string, b: boolean, ...c: string[]) {}

// Invalid: Rest parameter is not terminal
function invalidSignature(a: string, ...b: string[], c: boolean) {} 

// Invalid: Multiple rest parameters
function invalidMultiple(...a: string[], ...b: number[]) {}

Tuple Types in Rest Parameters

TypeScript allows rest parameters to be typed using tuple types. This enables highly specific type definitions for variadic arguments based on their positional index, combining fixed-length and variable-length type checking.
function processSequence(...args: [string, number, ...boolean[]]): void {
    const [str, num, ...bools] = args;
    // str is strongly typed as string
    // num is strongly typed as number
    // bools is strongly typed as boolean[]
}

// Valid invocation
processSequence("test", 42, true, false, true);

// Compiler Error: Expected at least 2 arguments, but got 1.
processSequence("test"); 
When using a tuple type for a rest parameter, TypeScript maps the tuple elements to discrete parameters during compilation, enforcing both the types and the minimum required arity of the function.
Master TypeScript with Deep Grasping Methodology!Learn More