Nahush Farkande
Nahush Farkande

Reputation: 5636

Infer parameter type in typescript

I am trying to construct a function which takes a class(Clazz) as an argument and returns an instance of the same class as follows

function myFunction(Clazz) {
    ...
    return new Clazz();
}

Is there any way to infer the type of Clazz and set it as the return type of this function? I am aware that I can probably acheive this using generics as follows:

function myFunction<T>(Clazz: new () => T): T {
    ...
    return new Clazz();
}

var instance = myFunction<myClass>(myClass)

But my intention is to get rid of that repitition of myClass as seen in the above usage

Upvotes: 0

Views: 69

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249536

Yes, just remove the <myClass> and you are good to go:

function myFunction<T>(Clazz: new () => T): T {
    return new Clazz();
}

class myClass {
    public m() { }
}
var instance = myFunction(myClass) // instance is typed as myClass, T is infered to myClass
instance.m() // ok 

Typescript will infer type parameters based on arguments to a function. It is rare you have to pass explicit type parameters (and is generally a sign of bad use of type parameters, not always, but generally).

Upvotes: 1

Related Questions