Introduction to Rest Parameters in TypeScript
Rest parameters allow a function to accept any number of arguments and collect them into a single array. They are useful when the number of values supplied to a function is not known in advance, such as calculating a total, combining strings, logging messages, or processing multiple records.
TypeScript extends JavaScript rest parameters with static type checking. You can specify the type of each collected argument so that the compiler detects incompatible values before the application runs.
Understanding rest parameters helps you write flexible functions without sacrificing type safety. They also work with function type aliases, callbacks, generics, and tuple types, making them valuable when designing reusable utilities and APIs.
1. What Are Rest Parameters?
A rest parameter uses three dots (...) before the parameter name. It collects all remaining arguments into an array that the function can process.
function sumNumbers(...numbers: number[]): number {
return numbers.reduce(
(total, current) => total + current,
0
);
}
console.log(sumNumbers(10, 20)); // 30
console.log(sumNumbers(1, 2, 3, 4)); // 10
console.log(sumNumbers()); // 0
In this example, ...numbers collects every supplied argument into an array of numbers. The function can therefore accept two arguments, four arguments, or no arguments at all.
The reduce() method adds the values together. Its initial value is zero, so an empty array also produces zero rather than causing an error.
Without rest parameters, you would need to declare a separate parameter for each supported argument or accept an array explicitly. Rest parameters allow callers to pass individual arguments while letting the implementation work with an array.
2. Rest Parameters with Type Annotations
In TypeScript, a rest parameter is annotated with an array type that describes the type of each collected argument. For example, number[] means that every argument collected by the parameter must be compatible with the number type.
function calculateAverage(
...scores: number[]
): number | undefined {
if (scores.length === 0) {
return undefined;
}
const total = scores.reduce(
(sum, score) => sum + score,
0
);
return total / scores.length;
}
console.log(calculateAverage(80, 90, 100));
console.log(calculateAverage(75, 85));
console.log(calculateAverage());
The return type is number | undefined because an average is not calculated when there are no scores. Representing that possibility in the return type makes the behavior clear to callers.
TypeScript reports a type error if a string is passed to this function because the rest parameter accepts numbers. Explicit array annotations are especially helpful when a function handles user scores, prices, measurements, or other values that must follow a known type.
3. Combining Required Parameters with Rest Parameters
A function can have ordinary parameters before a rest parameter. This allows you to require specific arguments while also accepting any number of additional values.
function logMessages(
category: string,
...messages: string[]
): void {
for (const message of messages) {
console.log("[" + category + "] " + message);
}
}
logMessages(
"INFO",
"Application started",
"Database connected",
"Server is ready"
);
The first argument is assigned to category. All remaining arguments are collected into messages, which is an array of strings.
This pattern is useful for logging utilities, notification systems, and functions that apply a shared setting to multiple values. The required parameter provides context, while the rest parameter supports a flexible number of inputs.
Required parameters must come before a rest parameter. A rest parameter must be the final parameter in an ordinary function signature because it collects all remaining positional arguments.
4. Rest Parameters with Strings
Rest parameters are not limited to mathematical operations. They can accept strings and combine them into a single result. This is useful for composing labels, messages, names, and descriptions.
function combineWords(
separator: string,
...words: string[]
): string {
return words.join(separator);
}
console.log(combineWords(" ", "TypeScript", "is", "useful"));
console.log(combineWords("-", "learn", "build", "improve"));
console.log(combineWords(", ", "HTML", "CSS", "JavaScript"));
The separator controls how the strings are joined, while the rest parameter provides any number of words. The join() method combines the elements into a single string.
Because the rest parameter is typed as string[], each supplied word must be a string. This keeps the function contract clear without requiring a separate parameter for every word.
5. Understanding Rest Parameters and Spread Syntax
Rest parameters and spread syntax both use three dots, but they perform different operations depending on where the syntax appears.
| Feature | Rest parameters | Spread syntax |
|---|---|---|
| Purpose | Collect arguments into an array | Expand an iterable or suitable value into elements |
| Common location | Function parameter declarations | Function calls, arrays, and object expressions |
| Example | ...values: number[] |
sum(...values) |
function sumNumbers(...numbers: number[]): number {
return numbers.reduce(
(total, current) => total + current,
0
);
}
const scores = [10, 20, 30];
// Spread expands the array into arguments.
console.log(sumNumbers(...scores)); // 60
In the function declaration, the rest parameter gathers arguments into an array. In the function call, spread syntax expands the array so that its elements are passed as individual arguments.
This distinction is important when writing reusable APIs. Rest parameters define how a function receives values, while spread syntax helps callers supply values from an existing collection.
6. Rest Parameters with Tuple Types
An array type specifies the type of every element in a collection. Sometimes a function needs a fixed sequence of argument types followed by additional arguments. TypeScript tuple types can describe this requirement more precisely.
function createCourseMessage(
...args: [title: string, duration: number, ...topics: string[]]
): string {
const [title, duration, ...topics] = args;
return (
title +
" lasts " +
duration +
" hours and covers " +
topics.join(", ")
);
}
console.log(
createCourseMessage(
"TypeScript",
8,
"Types",
"Functions",
"Generics"
)
);
The tuple type requires a string first, a number second, and allows additional string arguments afterward. TypeScript checks the argument positions, so callers cannot accidentally swap the title and duration.
Tuple-based rest parameters are useful when a function has a known argument structure combined with a variable number of additional values. They are also helpful for typing wrappers and utilities that preserve the signature of another function.
7. Rest Parameters in Function Type Aliases
A function type alias can define a rest parameter just like a regular function declaration. This lets you define reusable contracts for functions that accept a variable number of arguments.
type SumFunction = (...numbers: number[]) => number;
const sum: SumFunction = (...numbers) => {
return numbers.reduce(
(total, current) => total + current,
0
);
};
const multiply: SumFunction = (...numbers) => {
return numbers.reduce(
(total, current) => total * current,
1
);
};
console.log(sum(2, 3, 4));
console.log(multiply(2, 3, 4));
Both functions satisfy the SumFunction signature because they accept any number of numeric arguments and return a number. The type alias can be reused in configuration objects, callback parameters, and other function declarations.
Even though both implementations share the same type, their business behavior is different. Choose descriptive aliases when a particular operation has a meaningful domain-specific name, so the function contract remains understandable to other developers.
8. Using Rest Parameters with Generics
Generic rest parameters can preserve the individual types and positions of arguments rather than treating every collected value as the same type. This is useful for wrapping functions and forwarding arguments without losing the original signature.
function callFunction(
callback: (...args: TArgs) => TResult,
...args: TArgs
): TResult {
return callback(...args);
}
function describeCourse(
title: string,
duration: number
): string {
return title + " lasts " + duration + " hours";
}
const result = callFunction(
describeCourse,
"TypeScript Fundamentals",
8
);
console.log(result);
The generic tuple TArgs captures the parameter types of the callback. In this example, it represents a string followed by a number, so the arguments passed to callFunction must follow that same sequence.
The type parameter TResult preserves the callback's return type. As a result, the wrapper returns a string when the supplied function returns a string, rather than losing that information by using any.
This pattern is useful for logging wrappers, instrumentation, reusable execution helpers, and APIs that forward calls to another function. Generics allow the wrapper to support different function signatures while maintaining type safety.
9. Rest Parameters with Callback Functions
Rest parameters can be used when defining callbacks that receive multiple values. This is useful for event-processing utilities, logging, testing helpers, and functions that need to pass a variable number of arguments to another operation.
type MessageLogger = (
category: string,
...messages: string[]
) => void;
const logger: MessageLogger = (
category,
...messages
) => {
console.log(category + ":", messages.join(" | "));
};
logger("INFO", "Application started");
logger("ERROR", "Request failed", "Retry required");
The callback signature requires a category followed by any number of string messages. Implementations assigned to this type must remain compatible with that contract.
Use this pattern when a callback genuinely needs multiple individual arguments. If those values represent one structured record with named fields, an object parameter may be clearer and easier to extend over time.
10. Restrictions and Rules for Rest Parameters
Rest parameters follow specific language rules. Understanding these restrictions prevents invalid function declarations and helps keep the function signature predictable.
- A rest parameter must be last. It collects all remaining positional arguments, so another parameter cannot follow it.
- Only one rest parameter is allowed. A function cannot declare multiple rest parameters for the same argument list.
- The rest parameter is an array within the implementation. Its type must describe the collected values, such as
string[]ornumber[]. - The rest parameter itself cannot be optional. The collection can be empty, but it is always present as an array inside the function.
- Required parameters should precede the rest parameter. This makes the boundary between fixed arguments and collected arguments clear.
When a function needs a variable number of arguments with different types in specific positions, use a tuple type for the rest parameter instead of assuming all arguments have one common type.
11. When to Use Rest Parameters
Rest parameters are appropriate when a function naturally operates on a variable number of individual arguments. They are particularly useful for aggregation, formatting, callbacks, wrappers, and forwarding operations.
Numeric utilities
Functions such as summation, multiplication, and comparisons can accept multiple numeric inputs without requiring the caller to construct an array.
Logging and formatting
Logging helpers can receive a category followed by multiple messages, making the calling code concise and expressive.
Generic function wrappers
A wrapper can capture and forward arguments while preserving the original function's parameter and return types.
Flexible callback contracts
Callback types can accept a required context value followed by a variable number of additional arguments.
Rest parameters are not always the best choice. If your function needs structured options or a collection that is already stored in an array, accepting an object or array directly may be simpler. Choose the representation that best communicates the function's purpose.
Common Mistakes with Rest Parameters
Forgetting the array type
A rest parameter should have a type that describes its collected elements. Use types such as number[] or string[] when the arguments must share a type.
Placing parameters after the rest parameter
The rest parameter must appear last. Move fixed parameters before it or redesign the function signature.
Confusing rest with spread
Rest collects arguments into an array in a parameter declaration. Spread expands elements into individual values in a call or another supported expression.
Ignoring empty input
A rest parameter may contain zero elements. Make sure operations such as averages and lookups define suitable behavior for empty input.
Using rest for structured options
When arguments represent named settings, a typed options object may be easier to understand than a long positional call.
Conclusion
Rest parameters allow TypeScript functions to accept a variable number of arguments and collect them into a typed array. They are useful for mathematical utilities, string formatting, callbacks, logging, and reusable wrappers.
Start with simple array-based rest parameters, then explore tuple types when the argument positions have different types and generic rest parameters when forwarding function calls. Combine rest parameters with TypeScript function types to build flexible APIs that remain predictable, reusable, and type-safe.