Reputation: 4003
I'm trying to implement a factory in typescript that returns a generic type.
Already figured out that I need to pass the type as the first argument, and setting it's type to a CTOR signature (new () => T
in this example).
The problem begins when I want to pass a generic type to the factory - I get an error saying:
Value of type 'typeof G' is not callable. Did you mean to include 'new'?(2348)
.
Is there any way to achieve this?
Here is a simplified version of the problem:
// Generic class
class G<T>{}
// Standard non generic
class B{}
function make<T>(t: new () => T){
return new t()
}
// Works
make(B)
// Value of type 'typeof G' is not callable. Did you mean to include 'new'?(2348)
make(G<number>)
Typescript playground link to the above code.
Upvotes: 3
Views: 439
Reputation: 14844
Your issue is that you set the generic in the wrong place. In make(value)
, value
should be runnable code without any TypeScript definition. So the call make(G<number>)
is false because you can't call a TypeScript generic as a parameter.
To define the generic, you need to write it before the parenthesis:
make<G<number>>(G)
So here, G<number>
is the type that you give and G
is the 'valid' runnable code.
Have a look at the playground.
Upvotes: 3