简体   繁体   中英

Generics “New” constraint equivalent in TypeScript

In C#, you can do:

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM