open-ended function arguments with TypeScript
The TypeScript way of doing this is to place the ellipsis operator (...
) before the name of the argument. The above would be written as,
function sum(...numbers: number[]) {
var aggregateNumber = 0;
for (var i = 0; i < numbers.length; i++)
aggregateNumber += numbers[i];
return aggregateNumber;
}
This will then type check correctly with
console.log(sum(1, 5, 10, 15, 20));
In addition to @chuckj answer: You can also use an arrow function expression
in TypeScript (is kind of a lambda
in Java / .NET)
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}