How to instantiate a generic type in TypeScript

August 1, 2017, Software Development

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.

Tweet about this on TwitterShare on FacebookEmail this to someoneShare on TumblrShare on LinkedIn

Tags:

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](http://example.com)

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

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax