Paleo Paleo - 1 year ago 136
TypeScript Question

Generics in TypeScript: How to infer the type of an instance from the class

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) // OK

I would like to avoid the repetition of
. 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?

Answer Source

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);;

You don't need to specify the type of A anyway because the compiler know it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download