A factory function creates the instances of classes:
class A {
name: string
}
function factory<T>(Cl): T {
return new Cl()
}
let a = factory<A>(A)
a.name // OK
I would like to avoid the repetition of A
in: factory<A>(A)
. The generics instance type should be able to be inferred from the class type, shouldn't be?
I tried this code:
function factory<T>(Cl: typeof T): T { // Error: Cannot find name 'T'
return new Cl()
}
Is there a way to do this?
Based on the Typescript documentation :
When creating factories in TypeScript using generics, it is necessary to refer to class types by their constructor functions.
So you must do something like this:
function factory<T>(Cl: { new(): T; }): T {
return new Cl();
}
In the code above, Cl
must a type that at least has a constructor which return T
generic type.
So the type inference will work:
let a = factory(A);
a.name;
You don't need to specify the type of A
anyway because the compiler know it.