How to instantiate a generic type in TypeScript

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 Factory
    create<T>(type: (new () => T)): T {
        return new type();

let factory = new Factory();
let person = factory.create(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.


2 responses to “How to instantiate a generic type in TypeScript”

  1. Philippfx says:

    Great article 🙂

    How can I apply your strategy for array T[] ?

    Best regards,

    • Rico Suter says:

      Just cast a new array to T? E.g. let myArray = <T[]>[] and fill it with objects from the method above… however, I think the type T[] cannot be expressed in the JavaScript type system directly.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see