Вопрос

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
Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top