Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: types for variadic functions [duplicate]

Tags:

typescript

Possible Duplicate:
open-ended function arguments with TypeScript

Is there any acceptable type signature for variadic functions? Example:

function sum () {   var sum = 0;   for (var i = 0; i < arguments.length; i++) {     sum += arguments[i];   }   return sum; };  console.log(sum(1, 2, 3, 4, 5)); 

gives me compilation error:

foo.ts(9,12): Supplied parameters do not match any signature of call target 
like image 554
tensai_cirno Avatar asked Oct 02 '12 22:10

tensai_cirno


People also ask

Can variadic methods take any number of parameters?

A variadic function allows you to accept any arbitrary number of arguments in a function.

How do you access Variadic arguments?

To access variadic arguments, we must include the <stdarg. h> header.

What is variadic function in Javascript?

A variadic function is a function where the total number of parameters are unknown and can be adjusted at the time the method is called. The C programming language, along with many others, have an interesting little feature called an ellipsis argument.


1 Answers

In TypeScript you can use "..." to achive the above pattern:

function sum (...numbers: number[]) {   var sum = 0;   for (var i = 0; i <  numbers.length; i++) {     sum += numbers[i];   }   return sum; }; 

This should take care of your error.

like image 146
mohamed hegazy Avatar answered Oct 17 '22 05:10

mohamed hegazy