網站搜尋

angular - 如何使用類別建構函數為類別實例定義介面


我正在開發一個應用程式,部分程式碼允許開發者指定他們想要渲染某個部分的元件。我希望使用者知道他們需要實作一個介面,但我不確定如何正確地撰寫型別定義。

export interface ICustomComponent {
    templateObject: any;
}

export class MyComponent implements ICustomComponent {
}

export class MyLib {
    constructor(
        private yourComponent: ICustomComponent
    ) {}
}

new MyLib(MyComponent); <== Fails

我正在使用 Angular 撰寫程式碼,我無法使用 new 運算子,而是讓 Angular 解析並建構那個元件。

這裡有一個例子來說明我的問題。

如何處理這個問題?

答案#1

由於 MyLib 期望的是類別建構函數,而不是類別實例,因此你需要為類別建構函數定義一個介面,並指定它返回具有 ICustomComponent 介面的實例:

interface ICustomComponent {
  templateObject: any;
}

interface ICustomComponentConstructor {
  new (...deps: any[]): ICustomComponent;
}

然後你可以這樣使用它:

export class MyComponent implements ICustomComponent {
  templateObject: any;
}

export class MyLib {
  constructor(private yourComponent: ICustomComponentConstructor) {
  }
}

new MyLib(MyComponent);

你可以在這裡閱讀關於類別建構子和實例的介面。