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 number
s 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.