简体   繁体   English

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

[英]Generics “New” constraint equivalent in TypeScript

In C#, you can do: 在C#中,您可以执行以下操作:

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

In typescript, the closest I've managed to achieve is: 在打字稿中,我设法达到的最接近的是:

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

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


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

Any ideas how I can get it cleaner/closer to C# syntax? 有什么想法可以使它更清洁/更接近C#语法吗?

Do you want this to work for all classes? 您想让它适用于所有课程吗? If you have a super base class, it can be done in a simple way. 如果您有一个超级基类,则可以通过一种简单的方法来完成。

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