0

A basic use-case that illustrates what I'm doing:

class Foo {
  public constructor(arg1: number, arg2: number) {
    console.log(arg1);
    console.log(arg2);
  }
}

function foo(test: number): number[] {
  let args: number[] = [];
  for (let i = 0; i < 2; i++) {
    args.push(i);
  }
  if (args.length !== 2) {
    throw new Error('Invalid argument length');
  }
  return new Foo(...args);
}

console.log(foo(1));

When trying to run this, I get:

error TS2556: Expected 2 arguments, but got 0 or more.

16   return new Foo(...args);

Which I'm absolutely unable sure where to go to fix this.

1 Answer 1

1

Here is the error you are getting :

class Foo {
  public constructor(arg1: number, arg2: number) {
  }
}

declare let args: number[];
new Foo(...args); // expected 2 but got 0 or more. 

why

Because number[] can be an array of length 0 or more than 2. So it doesn't match [number,number] i.e. an array of exactly length 2.

Fix

Either annotate as a tupple [number,number]:

declare let args: [number,number];
new Foo(...args); // Ok

Or get the values from the array your self:

new Foo(args[0],args[1]);
Sign up to request clarification or add additional context in comments.

4 Comments

So if I have some number of different classes that all take a variable amount of arguments, there's no real way to use variable expansion here for the arguments as I'd always have to annotate it as a tuple of the appropriate length?
Or annotate as any. It is okay to use in a controlled manner when you want to do localized magic coding 👍
Casting or annotating as any doesn't seem to make a difference. I guess casting to a tuple of a specific length is the only way, other than using Reflect.construct() (which doesn't work in IE).
I figured it out—you can cast the class itself to any: new (Foo as any)(...args);

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.