13

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.

Community
  • 1
  • 1
1ambda
  • 1,145
  • 8
  • 19
  • 1
    Possible duplicate of [How to create a new object from type parameter in generic class in typescript?](http://stackoverflow.com/questions/17382143/how-to-create-a-new-object-from-type-parameter-in-generic-class-in-typescript) – Louis Dec 23 '16 at 00:00

1 Answers1

15

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();
Fenton
  • 241,084
  • 71
  • 387
  • 401