0
0
Typescriptprogramming~5 mins

Rest parameters with types in Typescript

Choose your learning style9 modes available
Introduction

Rest parameters let you collect many function arguments into one array. Using types helps keep your code safe and clear.

When you want a function to accept any number of arguments.
When you want to group extra arguments into an array for easy use.
When you want to make sure all extra arguments have the same type.
When you want to write flexible functions like sum or join that handle many inputs.
Syntax
Typescript
function functionName(...paramName: type[]) {
  // function body
}

The ... before the parameter name means it collects all extra arguments into an array.

Adding : type[] tells TypeScript what type the collected arguments should be.

Examples
This function adds any number of numbers given to it.
Typescript
function sum(...numbers: number[]) {
  return numbers.reduce((a, b) => a + b, 0);
}
This function greets each name passed as a string.
Typescript
function greetAll(...names: string[]) {
  names.forEach(name => console.log(`Hello, ${name}!`));
}
This function accepts strings or numbers and logs them.
Typescript
function logValues(...values: (string | number)[]) {
  values.forEach(value => console.log(value));
}
Sample Program

This program defines a function that multiplies all numbers passed to it. It shows how rest parameters collect numbers into an array and how the function works with different counts of arguments.

Typescript
function multiplyAll(...nums: number[]): number {
  return nums.reduce((product, num) => product * num, 1);
}

console.log(multiplyAll(2, 3));
console.log(multiplyAll(1, 4, 5));
console.log(multiplyAll());
OutputSuccess
Important Notes

Rest parameters must be the last parameter in the function.

You can only have one rest parameter per function.

TypeScript helps catch errors if you pass wrong types to rest parameters.

Summary

Rest parameters gather many arguments into an array.

Typing rest parameters keeps your code safe and clear.

Use rest parameters for flexible functions that handle many inputs.