0

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

Nahush Farkande
  • 5,290
  • 3
  • 25
  • 35
  • [As shown here](https://stackoverflow.com/a/26696435/6397798) you can avoiding the repetition by adding a type to the variable and let the compiler infer the type parameter for you, like this: `var instance: myClass = myFunction(myClass)` – bracco23 Jun 04 '19 at 08:07
  • @bracco23 that wouldn't be getting rid of the repition. I still have to type `myClass` twice – Nahush Farkande Jun 05 '19 at 05:03

1 Answers1

1

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

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357