Home > Software design >  How to call class constructor with some parameters omitted?
How to call class constructor with some parameters omitted?

Time:12-08

I'm trying to pass different combinations of arguments to a class constructor. The constructor takes 2 arguments that are both optional. Here is the code:

class MyClass {
  foo(a, b) {
    return new MyClass(a, b);
  }

  bar(a) {
    return new MyClass(a);
  }

  baz(b) {
    return new MyClass(b);
  }

constructor(a?: TypeA, b?: TybeB) {}
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The first two instantiations work, but the third attempt fails. It says: "Argument of TypeB is not assignable to parameter of TypeA". Baz(b) works if I rearrange the parameters of the constructor to become constructor(b?: TybeB, a?: TybeA), but now foo(a, b) fails.

Is there another way to do this?

CodePudding user response:

You need to call

return new MyClass(undefined, b);
  • Related