Rico Suter's blog.
 


In C# we can define a generic type argument and instantiate this type at runtime:

public class Factory
{
    public T Create<T>()
        where T: new()
    {
        return new T();
    }
}

var factory = new Factory();
var person = factory.Create<Person>();

But how would you write such a method in TypeScript? The main problem is, that the generic type argument T is not available at runtime because TypeScript generics are only used at compile time for type checking and removed in the transpiled JavaScript code.

The best solution I came up with, is to pass the generic type as method argument and add a generic type argument which will be inferred from the method argument and thus must not be declared:

class Person {
    firstName = 'John';
    lastName = 'Doe';
}

class Factory {
    create<T>(type: (new () => T)): T {
        return new type();
    }
}

let factory = new Factory();
let person = factory.create(Person);

console.log(JSON.stringify(person));

As you can see, the special part is the type (new () => T) which describes a type with an empty constructor. The call to create is almost as simple as in the C# example and you can also add constraints to the generic type argument if needed.



Discussion