Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a component class as an interface field in Typescript?

I have the following interface:

interface Drawer {
  title: string,
  content: Component
}

Afterwards I instantiate this interface:

let workspace: Drawer = {
    title: 'Workspaces',
    content: SidebarWorkspacesComponent
};

During compilation I get the following error:

ERROR in src/app/components/sidebar/sidebar-toggler.component.ts(36,4): error TS2559: Type 'typeof SidebarWorkspacesComponent' has no properties in common with type 'Component'.

Now I tried using ComponentRef and read dozens of articles but can't figure out how to pass a component in an interface. Obviously I could simply declare content as "any" but I would rather know how to do things properly.

Thanks in advance!

like image 942
Danny Coulombe Avatar asked Nov 23 '18 15:11

Danny Coulombe


2 Answers

Well, you can create an interface and then specify the type of content in the Drawer interface as that type. Something like this:

Here's that generic interface:

export interface GenericComponent {
  /*Your Specification Here*/
}

Then in your Drawer interface:

interface Drawer {
  title: string,
  content: GenericComponent
}

Now, you can assign any component that has implemented the GenericComponent interface on it to the Drawer interface's content.

So once you implement this GenericComponent interface on the SidebarWorkspacesComponent, you can then specify the type ofDrawer`'s content to it.


Here's a Sample StackBlitz for your ref.

like image 197
SiddAjmera Avatar answered Oct 16 '22 01:10

SiddAjmera


The closest would be to make your interface generic and change it to:

interface Drawer<T = any> {
  title: string,
  content: Type<T>
}

Using the Type<T> interface from @angular/core, as components dont really share a common interface, unless you enforce it by implementing a sort of placeholder interface.

An example of the previous approach is the dialog API from material, as it uses a similar interface in order to take component types as arguments.

like image 45
Jota.Toledo Avatar answered Oct 16 '22 02:10

Jota.Toledo