[英]How to define a component class as an interface field in 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<T = any> {
title: string,
content: Type<T>
}
使用@ angular / core中的Type<T>
接口 ,因為組件實際上不共享公共接口,除非您通過實現一種占位符接口來強制執行它。
好吧,您可以創建一個interface
,然后在Drawer
界面中指定該類型的content
類型。 像這樣的東西:
這是通用接口:
export interface GenericComponent {
/*Your Specification Here*/
}
然后在你的Drawer
界面中:
interface Drawer {
title: string,
content: GenericComponent
}
現在,您可以將已實現GenericComponent
接口的任何組件分配給Drawer接口的content
。
因此,一旦在SidebarWorkspacesComponent上實現此GenericComponent
接口, you can then specify the type of
Drawer`的內容, you can then specify the type of
。
這是你的ref的Sample StackBlitz 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.