簡體   English   中英

TypeScript中的泛型“ New”約束等效

[英]Generics “New” constraint equivalent in TypeScript

在C#中,您可以執行以下操作:

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

在打字稿中,我設法達到的最接近的是:

class ItemFactory<T>{
  instantiatibleModel : new() => T;

  constructor(modelWithctor : { new(): T }){
    this.instantiatibleModel = modelWithctor;
  }


  GetNewItem() : T{
     return new this.instantiatibleModel();
   }
}

有什么想法可以使它更清潔/更接近C#語法嗎?

您想讓它適用於所有課程嗎? 如果您有一個超級基類,則可以通過一種簡單的方法來完成。

class Base {
    hi() {
        alert('base');
    }
}
class Derived extends Base {
    hi() {
        alert('Der');
    }
}
class Gen<T extends Base >{
    constructor(private testType) {
    }
 create<T>(): T { 
    return new this.testType();
 }
}
var g=new Gen<Derived>(Derived);
var obj= g.create();

暫無
暫無

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

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