Rest Parameters in TypeScript
Learn how to pass multiple arguments to a function using rest parameters, collect arguments into an array, and perform calculations with a flexible number of inputs.
What Are Rest Parameters?
Normally, a function can declare a fixed number of parameters. Sometimes, however, we need to pass a different number of arguments whenever the function is called.
TypeScript provides rest parameters to handle this requirement. All remaining arguments are collected into an array.
-
Rest parameters use the
...syntax. - They collect multiple arguments into an array.
- The number of arguments can vary between calls.
- A rest parameter must be the last parameter in a function's parameter list.
- Rest parameters are useful for totals, averages, search operations, and other calculations.
Rest Parameters Workflow
The following diagram shows how multiple arguments are collected and processed by a function.
Step 1
Pass ArgumentsSupply multiple values to the function.
Step 2
Collect ValuesStore remaining arguments in an array.
Step 3
Process ArrayCalculate or process the collected values.
Step 4
Return ResultDisplay or return the final result.
Example of Argument Collection
10, 20, 30, 40
...numbers
[10, 20, 30, 40]
1. Syntax of Rest Parameters
A rest parameter is declared by placing three dots before the parameter name. In TypeScript, we can specify the array element type.
Syntax
function functionName(...parameters: number[]): void {
// Function statements
}
Example
function displayNumbers(...numbers: number[]): void {
console.log(numbers);
}
displayNumbers(10, 20, 30);
displayNumbers(5, 15, 25, 35, 45);
Expected Output
[ 10, 20, 30 ]
[ 5, 15, 25, 35, 45 ]
Explanation
-
...numbersdeclares the rest parameter. -
number[]specifies that the collected arguments form an array of numbers. - The first call collects three numbers.
- The second call collects five numbers using the same function.
2. Calculate the Sum Using Rest Parameters
Rest parameters are useful when we want to calculate the sum of any number of values.
Example
function calculateSum(...numbers: number[]): number {
let sum: number = 0;
for (const number of numbers) {
sum += number;
}
return sum;
}
console.log(calculateSum(10, 20));
console.log(calculateSum(10, 20, 30));
console.log(calculateSum(5, 10, 15, 20));
Expected Output
30
60
50
Explanation
- The function accepts any number of numeric arguments.
-
The
for...ofloop visits every number. -
Each number is added to the
sumvariable. - The function returns the final sum.
3. Calculate Average Using Rest Parameters
We can use a rest parameter to calculate the average of multiple numbers. The function should also handle the case where no numbers are supplied.
Example
function calculateAverage(...numbers: number[]): number {
if (numbers.length === 0) {
return 0;
}
let sum: number = 0;
for (const number of numbers) {
sum += number;
}
return sum / numbers.length;
}
console.log(calculateAverage(10, 20, 30));
console.log(calculateAverage(70, 80, 90, 100));
console.log(calculateAverage());
Expected Output
20
85
0
Explanation
- First, the function checks whether the array is empty.
- If no arguments are provided, it returns 0.
- Otherwise, it adds all numbers and divides the sum by the number of values.
- The result is returned as a number.
4. Required Parameters with Rest Parameters
A function can have ordinary parameters followed by a rest parameter. The rest parameter must always appear last in the parameter list.
Example
function displayStudentMarks(
studentName: string,
...marks: number[]
): void {
console.log("Student:", studentName);
console.log("Marks:", marks);
}
displayStudentMarks("Rahul", 75, 80, 90);
displayStudentMarks("Priya", 85, 95);
Expected Output
Student: Rahul
Marks: [ 75, 80, 90 ]
Student: Priya
Marks: [ 85, 95 ]
Explanation
-
studentNameis the required parameter. -
...markscollects all remaining numeric arguments into an array. - Each student can have a different number of marks supplied to the function.
5. Rest Parameters with Strings
Rest parameters can also collect strings. The type annotation defines the type of every collected value.
Example
function displayCourses(...courses: string[]): void {
for (const course of courses) {
console.log(course);
}
}
displayCourses("Java", "Python", ".NET");
Expected Output
Java
Python
.NET
Explanation
The function collects all course names into a string
array and then displays each course using a
for...of loop.
6. Rest Parameters vs Array Parameter
Rest parameters and array parameters both allow a function to work with multiple values, but they are called differently.
A. Using Rest Parameters
function displayNumbers(...numbers: number[]): void {
console.log(numbers);
}
displayNumbers(10, 20, 30);
B. Using an Array Parameter
function displayArray(numbers: number[]): void {
console.log(numbers);
}
displayArray([10, 20, 30]);
Difference
| Rest Parameters | Array Parameter |
|---|---|
Uses ...numbers: number[]. |
Uses numbers: number[]. |
| Accepts separate arguments. | Accepts an array as an argument. |
displayNumbers(10, 20, 30) |
displayArray([10, 20, 30]) |
| Arguments are collected into an array. | The supplied array is received as the parameter value. |
7. Practical Example: CIIT Student Results
Let's create a function that accepts a student name and any number of subject marks, then calculates the total marks.
Example
function calculateStudentTotal(
studentName: string,
...marks: number[]
): number {
let total: number = 0;
for (const mark of marks) {
total += mark;
}
console.log("Student:", studentName);
console.log("Subject Marks:", marks);
return total;
}
const totalMarks: number =
calculateStudentTotal("Priya", 85, 90, 88, 92);
console.log("Total Marks:", totalMarks);
Expected Output
Student: Priya
Subject Marks: [ 85, 90, 88, 92 ]
Total Marks: 355
Explanation
- The function receives the student's name first.
-
All remaining numeric arguments are collected
in the
marksarray. - The loop calculates the total marks.
- The total is returned to the calling code.
Common Mistakes
- Forgetting the three dots before the rest parameter.
- Using the wrong array element type.
- Placing another parameter after the rest parameter.
- Confusing a rest parameter with an ordinary array parameter.
- Forgetting to handle an empty array when calculating an average or another value that requires elements.
Practice Task
Write TypeScript functions to complete the following tasks.
- Create a function that accepts any number of arguments and returns their sum.
- Create a function that calculates the average of multiple numbers.
- Create a function that accepts a student's name and multiple subject marks.
- Create a function that accepts multiple course names and displays them one by one.
- Create a function with one required parameter followed by a rest parameter.
Summary
In this lesson, we learned how to declare rest parameters using three dots, collect multiple arguments into arrays, calculate sums and averages, work with strings, and combine rest parameters with required parameters. Rest parameters make functions flexible when the number of arguments varies.