11

I have a method that should accept either an array of numbers or accept a variable number of number arguments (variadic). In most languages I've used, when you make a method/function variadic, it accepts both, but it seems that in TypeScript, you cannot. When I make this particular function variadic, all of the places where I supply a number[] fail compilation.

Signature for reference (in class ObjectIdentifier):

constructor(... nodes : number[]) {

This fails:

return new ObjectIdentifier(numbers);

where numbers is of type number[].

Jonathan Wilbur
  • 1,057
  • 10
  • 19

2 Answers2

20

Use the following syntax:

const func = (...a: number[]) => console.info('a', a)

func(1, 2, 3)

func(...[1, 2, 3])
kemsky
  • 14,727
  • 3
  • 32
  • 51
3

Here is one approach:

class ObjectIdentifier {
  public myNodes: number[];
  constructor(first?: number | number[], ...rest: number[]) {
    this.myNodes =
      first === undefined
        ? []
        : first instanceof Array
          ? [...first, ...rest]
          : [first, ...rest];
  }
}
const empty = new ObjectIdentifier();
const a = new ObjectIdentifier(1);
const b = new ObjectIdentifier([1]);
const c = new ObjectIdentifier(1, 2, 3);
const d = new ObjectIdentifier([1, 2, 3]);
const e = new ObjectIdentifier([1, 2, 3], 4, 5, 6);

The only quirk is seen in that last case where you can pass an array as the first parameter followed by a variable number of numbers.

Brian Adams
  • 43,011
  • 9
  • 113
  • 111
  • This should only be used if you can't control that you are being called in both ways, otherwise just use the spread operator when passing an array – Brian Adams Aug 12 '18 at 13:31