How to instantiate a generic type in TypeScript

August 1, 2017, (updated on October 12, 2018), 10 comments, 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 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);


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.


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

  1. Dmitry says:

    What if I need to create generic type instance within generic class?

    class BaseService<T>{
        private foo() {
            let bar: T;
            bar = ...

    In this case Factory.create(T) will not work – “T only refers to a type, but is being used as value here”

  2. Siva Nomula says:

    Thanks!!! here is the sample code code the dynamic response

    getData() {

    return this.http

    .get(url, { headers: this.headers })

    .map(p => this.handleResponse(p, ReportReviewSummary))



    private handleResponse(response: any, type: (new (any) => T)): T {

    if (response.text() === ”) {

    return new type(null);

    } else {

    return new type(response.json());



  3. 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 created with 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.