簡體   English   中英

您可以在實現另一個接口的組件的接口中鍵入字段嗎?

[英]Can you type a field in an interface to a Component that implements another interface?

我已經為我的組件創建了要實現的接口,以便為此類型創建的每個組件都具有相同的字段。 然后,我有另一個接口,該接口的字段需要這種類型的組件。

我已經創建了這些接口並設置了相應的組件和對象,但是仍然出現以下錯誤:

Type 'typeof MyComponent' cannot be assigned to type 'ComponentShouldImplementThis<T>'. Property 'someField' is missing in type 'typeof MyComponent'.

我的界面:

export interface ComponentShouldImplementThis<T> {
  someField: string;
}

export interface ContainsFieldComponentInterface<T> {
  component: ComponentShouldImplementThis<T>;
}

我的組件:

@Component({
 selector: 'mycomponent',
 template: '<div>Hello</div>'
})
export class MyComponent implements ComponentShouldImplementThis<any> {
  someField: string;
  constructor(){}
}

我對我大吼的對象:

let implementedInterface: ContainsFieldComponentInterface = {
  component: MyComponent
}

當實現ComponentShouldImplementThis時, someField滿足IDE,但是不喜歡具有用於實現它的組件的接口。

我要進行角度編譯的事情是代替組件的一個實例:

let implementedInterface: ContainsFieldComponentInterface = {
  component: new MyComponent
}

但這會在下游引起其他問題。 這是正確的實現嗎? 不知道我要去哪里錯了。

angular/core中有一個表示組件的類型: https : //angular.io/api/core/Type

用法:

export interface ContainsFieldComponentInterface<T> {
  component: Type<ComponentShouldImplementThis<T>>;
}

為什么您的類型信息不起作用? 您可能還記得JS / TS中的類是創建對象的函數(或構造函數)。 您可以在界面中指定創建對象的類型(驗證創建的對象將具有類的所有屬性)。 如果想縮小可能的構造函數,則必須創建另一種類型:

type OfSpecificType<T> = {
   new (...args: any[]): T
}

此簽名意味着調用OfSpecificType類型的函數將返回類型T

因此,您的界面最終看起來像:

export interface ContainsFieldComponentInterface<T> {
  component: OfSpecificType<ComponentShouldImplementThis<T>>;
}

但這與使用angular/coreType<T>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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