5

I'm looking to create an object based on a generic type, but can't figure out the syntax. What I'm wanting is something like this contrived example:

myfunc<T>() : T[] {
    let obj = new T();
    let obj2 = new T();

    return [obj, obj2];
}

The new T() of course doesn't compile. In C# I'd add a where T : new constraint to make that work. What's the equivalent in TypeScript?

Grokify
  • 15,092
  • 6
  • 60
  • 81
Gargoyle
  • 9,590
  • 16
  • 80
  • 145
  • 2
    Possible duplicate of [How to create a new object from type parameter in generic class in typescript?](https://stackoverflow.com/questions/17382143/how-to-create-a-new-object-from-type-parameter-in-generic-class-in-typescript) – jcalz Jun 13 '18 at 18:37

1 Answers1

9

You have to remember that TypeScript types (including generics) only exist at compile time. Also, in JavaScript the constructor function is of a different type that the object it constructs.

You probably are looking for something like this (assuming your constructor takes zero parameters):

function foo<T>(C: { new(): T }): T[] {
    return [new C(), new C()];
}

class SomeClass {}

// here you need to pass the constructor function
const array = foo(SomeClass);

There, C is the constructor function you will use at runtime and T is a type that will be inferred as the resulting of the construction.

Daniel
  • 2,657
  • 1
  • 17
  • 22