Categories
TypeScript Answers

How to create a function that accept an unlimited number of arguments with TypeScript?

Spread the love

Sometimes, we want to create a function that accept an unlimited number of arguments with TypeScript.

In this article, we’ll look at how to create a function that accept an unlimited number of arguments with TypeScript.

How to create a function that accept an unlimited number of arguments with TypeScript?

To create a function that accept an unlimited number of arguments with TypeScript, we can use the rest syntax.

For instance, we write

const sum = (...nums: number[]): number => {
  return nums.reduce((a, b) => a + b, 0);
};

to create the sum function that accepts an unlimited arguments by using the ... rest operator before nums.

nums is an array of numbers and it has all the arguments that we passed into it.

We set the nums parameter to number[] to make the type explicit.

Conclusion

To create a function that accept an unlimited number of arguments with TypeScript, we can use the rest syntax.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *