如何在 Typescript 中将组件类定义为接口字段?

Dan*_*mbe 6 typescript angular-components angular

我有以下界面:

interface Drawer {
  title: string,
  content: Component
}
Run Code Online (Sandbox Code Playgroud)

之后我实例化这个接口:

let workspace: Drawer = {
    title: 'Workspaces',
    content: SidebarWorkspacesComponent
};
Run Code Online (Sandbox Code Playgroud)

在编译期间,我收到以下错误:

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'.
Run Code Online (Sandbox Code Playgroud)

现在我尝试使用 ComponentRef 并阅读了数十篇文章,但无法弄清楚如何在接口中传递组件。显然我可以简单地将内容声明为“任何”,但我宁愿知道如何正确地做事。

提前致谢!

Sid*_*era 4

那么,您可以创建一个,然后在接口中interface指定 的类型作为该类型。像这样的东西:contentDrawer

这是通用界面:

export interface GenericComponent {
  /*Your Specification Here*/
}
Run Code Online (Sandbox Code Playgroud)

然后在你的Drawer界面中:

interface Drawer {
  title: string,
  content: GenericComponent
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以将任何已实现该GenericComponent接口的组件分配给 Drawer 接口的content.

因此一旦你GenericComponent在 SidebarWorkspacesComponent , you can then specify the type ofDrawer` 的内容上实现了这个接口就可以了。


这是一个StackBlitz 示例供您参考。