簡體   English   中英

如何在Typescript中將組件類定義為接口字段?

[英]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>接口 ,因為組件實際上不共享公共接口,除非您通過實現一種占位符接口來強制執行它。

前一種方法的一個示例是來自材料對話API ,因為它使用類似的接口以將組件類型作為參數。

好吧,您可以創建一個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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM