Type mismatch when passing component as variable to ngx-bootstrap modal service

42 Views Asked by At

I'm following the example here to create an ngx-bootstrap modal from a component.

However, if I create a variable for the component using the ternary operator, I get a weird compiler error if I don't declare my variable separately from assigning it.

In other words, this works:

let modal;
modal = someParameter ? FooComponent : BarComponent;
this.bsModalRef = this.bsModalService.show(modal);

(Note that both FooComponent and BarComponent extend a common base class.)

But if I try this:

let modal = someParameter ? FooComponent : BarComponent;
this.bsModalRef = this.bsModalService.show(modal);

I get a compile-time error like:

TS2345: Argument of type 'typeof FooComponent | typeof BarComponent' is not
assignable to parameter of type 'string | TemplateRef<any> |
(new (...args: any[]) => BarComponent)'.

Type 'typeof BarComponent' is not assignable to type 'string | TemplateRef<any> |
(new (...args: any[]) => FooComponent)'.

Types of construct signatures are incompatible.

There follows some additional complaining that the two subclasses don't share identical properties.

What seems to be happening is that compiler is randomly picking one class or another as the type signature to test against, rather than honoring the | which it seems to recognize in the initial part of the error message. But I don't understand why, or why separating the declaration from the assignment makes the problem go away.

Any input is appreciated.

1

There are 1 best solutions below

3
Naren Murali On

You can either use multiple this.modalService.open() for each of the components, but seems like a ineffecient way to resolve your problem, so I would suggest you convert the type to one of the components, this will resolve your issue!

Note this type is only used to open the modal, it wont interfere with the typing anywhere else, in the modal component!

this.bsModalRef = this.modalService.show(
  (this.test
    ? ModalContentComponent
    : ModalContentTwoComponent) as typeof ModalContentComponent
);

stackblitz