12

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[].

1

2 Answers 2

23

Use the following syntax:

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

func(1, 2, 3)

func(...[1, 2, 3])
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.