48

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
1

1 Answer 1

70

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I guess it doesn't support the multiple type feature? For example, this will not compile: foo(...item: string[] | number[])
@Lee it won't swallow string[] | number[], but (number|string)[] is perfectly ok (although you will likely need to do some casting inside function body).
or ...numbers: Array<number | string>
you could also make it a template function if you want to specify they're all the same: function sum<T extends number | string>(...item: Array<T>): T

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.