泛型“新"TypeScript中的约束等效项 [英] Generics "New" constraint equivalent in TypeScript

查看:56
本文介绍了泛型“新"TypeScript中的约束等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有什么想法可以使它更清洁/更接近C#语法?

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

这篇关于泛型“新"TypeScript中的约束等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆