Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  188] [ 1]  / answers: 1 / hits: 103901  / 12 Years ago, tue, october 2, 2012, 12:00:00

IMO, one of the main concerns of the TypeScript language is to support the existing vanilla JavaScript code. This is the impression I had at first glance. Take a look at the following JavaScript function which is perfectly valid:




Note: I am not saying that I like this approach. I am just saying this is a
valid JavaScript code.




function sum(numbers) { 

var agregatedNumber = 0;
for(var i = 0; i < arguments.length; i++) {
agregatedNumber += arguments[i];
}

return agregatedNumber;
}


So, we consume this function with any number of arguments:



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


However, when I try this out with TypeScript Playground, it gives compile time errors.



I am assuming that this is a bug. Let's assume that we don't have the compatibility issues. Then, is there any way to write this type of functions with open-ended arguments? Such as params feature in C#?


More From » typescript

 Answers
26

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));

[#82785] Monday, October 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devinjadong

Total Points: 711
Total Questions: 117
Total Answers: 100

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
devinjadong questions
Thu, Feb 17, 22, 00:00, 2 Years ago
Wed, Dec 8, 21, 00:00, 2 Years ago
Tue, Oct 27, 20, 00:00, 4 Years ago
Fri, Oct 18, 19, 00:00, 5 Years ago
;