Gargoyle
Gargoyle

Reputation: 10294

TypeScript create object from generic type

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?

Upvotes: 5

Views: 8911

Answers (1)

Daniel
Daniel

Reputation: 2767

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.

Upvotes: 9

Related Questions