Consider the following scenario:
class Foo {
}
You have a function that takes a type-parameterized class as an argument:
function bar<TInstance, TClass extends { new (): TInstance }>(t: TClass): TInstance {
return new t() // Actually more complex in reality, but let's focus on the compiler!
}
When calling this function with a class constructor, there are no type complaints:
const x = bar(Foo)
However, the type of x
ends up being {}
, not Foo
.
If you provide explicit type parameters, the issue is resolved:
const x = bar<Foo, typeof Foo>(Foo)
... but this seems like unnecessary repetition.
Is there a way to achieve type inference in this situation, eliminating the need for repetitive code?