簡體   English   中英

TypeScript可以定義這個類型嗎?

[英]Is it possible to define this type in TypeScript?

我正在創建一個 TypeScript 應用程序。 我的想法是將一種功能傳遞給我的應用程序。 每個功能都是 class,但尚未實例化。 在我的應用程序中還有一個特殊的方法“init”,我想在其中傳遞真實的特征對象。

這個怎么定義?

如果我像這樣定義泛型類型:

Application<F extends Record<string, Feature>>

然后 TS 要我將實例傳遞給我的類型。 我如何定義這種類型是類的記錄,然后我將能夠創建一個新類型來反映原始類型的結構但具有實例?

要傳入 class,您需要傳入 class 的構造函數。您可以使用構造函數簽名來執行此操作(類似於 function 簽名,只是在其前面加上關鍵字new


class Application<F extends Record<string, new () => Feature>> {
  
  constructor(feautures: F) {
    for(let key in feautures) {
      let f= new feautures[key]();
      f.init()
    }
  }
}


new Application({
  FeatureA,
  FeatureB
})

游樂場鏈接

或者,如果您想更輕松地訪問實例類型,您還可以使用:


class Application<F extends Record<string, Feature>> {
  featureInstances: F;  
  constructor(feautures: { [P in keyof F]: new () => F[P] }) {
    this.featureInstances = {} as F
    for(let key in feautures) {
      let f= new feautures[key]();
      f.init()
      this.featureInstances[key] = f
    }
  }
}

let app = new Application({
  FeatureA,
  FeatureB
})
app.featureInstances.FeatureA.methodA();
app.featureInstances.FeatureB.methodB();

游樂場鏈接

暫無
暫無

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

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