angulartypescriptclassinterfaceangular-dynamic-components

Is there a way to store the class reference in a variable to instantiate the same later


I need to force a class to implement a method say okClick so I created an interface

interface BaseComponent {
  okClick(): void
}

and made my class implement the same.

class ComponentImplementation implements BaseComponent {
  okClick(): void {
    // ok button clicked
  }
}

Further, I need this (and other similar ) components to be dynamically created using Angular's createComponent(), so I store the same in a variable of type BaseComponent

class Implementation {
  // TS2741: Property 'okClick' is missing in type 'typeof ComponentImplementation' but required in type 'BaseComponent'.
  tempVar: BaseComponent = ComponentImplementation

  constructor() {
    // dynamically create the Angular component from tempVar
  }
}

The class assignment to the variable tempVar above fails to find the okClick function.

Please suggest, what should be the type of tempVar to be able to hold the definition of classes implementing BaseComponent.


Solution

  • By specifying that tempVar is of type BaseComponent, it is telling TypeScript that you expect tempVar to be an instance of BaseComponent, not that it is a constructor that returns a BaseComponent. You can see that in the error: it says that "onClick" (an instance method) is not available on the type "typeof ComponentImplementation" (the constructor function). In fact, you get the same error if you try to specify that tempVar: ComponentImplementation.

    If BaseComponent were a class, you could specify that tempVar was typeof BaseComponent, but since it's just an interface you can't. (In the tempVar: ComponentImplementation variation, tempVar: typeof ComponentImplementation works).

    You could add another interface for a BaseComponentConstructor:

    interface BaseComponentConstructor {
        new(): BaseComponent
    }
    

    then specify that tempVar is of that type:

    tempVar: BaseComponentConstructor = ComponentImplementation