Open In App

TypeScript Rest Arguments

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript rest arguments use the spread operator (...) to capture a variable number of function arguments into an array. This allows for flexible operations like merging, concatenating, or processing multiple inputs dynamically within a single function.

Syntax

function function_name(...rest: type[]) {
  // Type of the is the type of the array. 
}

Example 1: Sum of Integer Arguments

In this example, we will calculate the sum of integer arguments passed to a function using the rest parameter syntax.

JavaScript
function getSum(...numbers: number[]): number {
	let sum = 0;
	numbers.forEach((num) => sum += num);
	return sum;
}

// Function call
console.log(getSum(10, 50, 30));
console.log(getSum(-50, 50, -10, 5));

Output:

90
-5

Example 2: Concatenating Strings

In this example, we will concatenate several strings passed to a function as arguments

JavaScript
let generateGreeting =
	(
		greeting: string,
		...names: string[]
	)
		: string => {
		return greeting + " " +
			names.join(", ") + "!";
	}

// Function call
console.log(
	generateGreeting("Hello ", "GeeksforGeeks ",
		"ABCD ", "Apple")
);

Output:

Hello  GeeksforGeeks , ABCD , Apple!

Conclusion

TypeScript rest arguments provide a flexible way to handle functions that can accept a variable number of arguments. By using the spread operator ..., you can capture these arguments into an array, allowing for operations such as summing integers or concatenating strings. This feature enhances the capability to write more dynamic and versatile functions in TypeScript.


Next Article

Similar Reads