I have a base class and multiple classes that extend that base class which all have a private constructor.
I now want to create a static function that creates new instances of the extending classes. Normally I would have a function header of something like this:
public static createInstance<T extends BaseClass>(clazz: { new(): T }): T
When I want to use this function:
createInstance(CustomClass)
It causes typescript to spit out this error:
TS2345: Argument of type 'typeof CustomClass' is not assignable to parameter of type 'new () => CustomClass'. Cannot assign a 'private' constructor type to a 'public' constructor type.
The code actual transpiled code is working perfectly fine.
I know what this error is telling me. But I cannot find a way around this. I've searched a lot and I seem to be very alone with this problem. Is there any way to reference classes with private constructors?
The solution to your issue is surprizingly simple: instead of constraining the generic type parameter
Tto an instance type of theBaseclass, constrain it to the static (or constructor) side of it via thetypeof Basetype query.This will ensure that
clazzwill be inferred as the constructor type of the concrete type ofTinstead of the public constructor type (new (): T), effectively bypassing the private constructor check while retaining the benefits of the generic constraint:Playground