在TypeScript中从泛型类型获取构造函数/实例 [英] Get constructor/instance from generic type in TypeScript

查看:2289
本文介绍了在TypeScript中从泛型类型获取构造函数/实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从泛型类型 T 创建实例,例如,

 <$ c (); T {
return new T();




$ b $ p $但是既然 T
code>只是类型而不是构造函数,我们不能这样做。

无法在TypeScript中从泛型创建实例?



我也阅读过这些文章,但找不到解决方案。




解决方案

如果在调用 new T()时,关于 T 的信息不可用$ c $。

这就是为什么所有替代解决方案都依赖于传递的构造函数,比如这个动态创建类的例子

  interface ParameterlessConstructor< T> {
new():T;


class ExampleOne {
hi(){
alert('Hi');
}
}

class Creator< T> {
构造函数(private ctor:ParameterlessConstructor< T>){

}
getNew(){
return new this.ctor();
}
}

var creator = new Creator(ExampleOne);

var example = creator.getNew();
example.hi();


I am trying to create instance from generic type T for example,

class Factory {
    public static generate<T>(): T { 
      return new T();
  }
}

But since T is just a type not constructor, we can't do that.

Is it impossible to create an instance from a generic type in TypeScript?

I'v also read these articles but could not found a solution.

解决方案

The type information used in TypeScript is erased before runtime, so the information about T is not available when you make the call to new T().

That's why all of the alternate solutions depend upon the constructor being passed, such as with this example of creating a class dynamically:

interface ParameterlessConstructor<T> {
    new (): T;
}

class ExampleOne {
    hi() {
        alert('Hi');
    }
}

class Creator<T> {
    constructor(private ctor: ParameterlessConstructor<T>) {

    }
    getNew() {
        return new this.ctor();
    }
}

var creator = new Creator(ExampleOne);

var example = creator.getNew();
example.hi();

这篇关于在TypeScript中从泛型类型获取构造函数/实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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