How to refer to a class with private constructor in a function with generic type parameters?


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:


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 T to an instance type of the Base class, constrain it to the static (or constructor) side of it via the typeof Base type query.

This will ensure that clazz will be inferred as the constructor type of the concrete type of T instead of the public constructor type (new (): T), effectively bypassing the private constructor check while retaining the benefits of the generic constraint:

abstract class Abstract {}

class Base { answer = 42; }

class Custom extends Base {
  private constructor() { super(); }

class Unrelated {}

declare function createInstance<T extends typeof Base>(clazz: T): T;

createInstance(Abstract); // error, OK
createInstance(Base); // OK
createInstance(Custom); // OK
createInstance(Unrelated); // error, OK


Answered By – Oleg Valter is with Ukraine

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published