Get constructor/instance from generic type in TypeScript

前端 未结 1 1864
野的像风
野的像风 2020-12-16 17:48

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

class Factory {
    public static generate(): T { 
      return new T()         


        
相关标签:
1条回答
  • 2020-12-16 17:50

    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();
    
    0 讨论(0)
提交回复
热议问题