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



我有以下接口:

interface Drawer {
title: string,
content: Component
}

然后我实例化这个接口:

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

在编译过程中,我得到以下错误:

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'.

现在我尝试使用ComponentRef,阅读了几十篇文章,但不知道如何在接口中传递组件。显然,我可以简单地将内容声明为"任何",但我更愿意知道如何正确地做事。

提前感谢!

您可以创建一个interface,然后在Drawer接口中将content的类型指定为该类型。类似这样的东西:

这是通用接口:

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

然后在您的Drawer界面中:

interface Drawer {
title: string,
content: GenericComponent
}

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

因此,一旦你在边栏工作空间组件, you can then specify the type of抽屉的内容上实现了这个GenericComponent接口。


这是一个样品堆栈闪电供您参考。

最接近的方法是使您的接口通用,并将其更改为:

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

使用@angular/core中的Type<T>接口,因为组件并没有真正共享一个公共接口,除非您通过实现一种占位符接口来强制执行它。

前面方法的一个例子是来自material的对话框API,因为它使用类似的接口以将组件类型作为参数。

最新更新