Search code examples
angulartypescriptinterfacecomponentstypechecking

Typechecking Components that implement an Interface


In Angular, I want to specify the type for a component that implements a certain interface that I pass into a class.

Example: Class A has this signature

class A {
  constructor(public component: ?) {}
}

Then we declare an interface I

export interface I<T> {
  setData(data: T): void;
}

The component B implements the interface I

class B implements I<string> {
  setData(data: string) { ... }
}

Now the problem is that not only component B implements I, but also component C, D and E. Furthermore class A should be able to process the components B,C,D and E, i.e. all components that implement interface I. Can I specify in class A that the component type is any component that implements interface I? My solution right now is

component: any

But I would like to specify that it can be any with the restriction that it implements I.

Is there another way to do it?


Solution

  • The following worked for me:

    class A {
      constructor(public component: new (...args: any[]) => I<any>)
    }