How to add open-ended function arguments with TypeScript?

Sometimes, we want to add open-ended function arguments with TypeScript.

In this article, we’ll look at how to add open-ended function arguments with TypeScript.

How to add open-ended function arguments with TypeScript?

To add open-ended function arguments with TypeScript, we can use the rest syntax.

For instance, we write

const sum = (...numbers: number[]) => {
  let aggregateNumber = 0;
  for (const n of numbers) {
    aggregateNumber += n;
  }
  return aggregateNumber;
};

console.log(sum(1, 5, 10, 15, 20));

to create the sum function.

We make it accept an unlimited number of arguments with ...numbers.

And we get the arguments as an array.

We set the type to number[] so that numbers would be an array of numbers.

Then we loop through the numbers entries and add them to aggregateNumber.

And finally, we return the result.

Conclusion

To add open-ended function arguments with TypeScript, we can use the rest syntax.