Search code examples
typescriptprivate-constructor

Accessing a private constructor


I have a Typescript class with a private constructor:

class Foo {
  private constructor(private x: number) {}
}

For testing purposes I would like to call this constructor from outside the class (please don't argue this point). Typescript provides an escape method for accessing private fields, like foo["x"] (see this other question) but I can't figure out the syntax for calling the constructor. It should be something like this right?

const f = new Foo["constructor"](5);

But that doesn't work. What's the correct syntax?


Solution

  • You could assert Foo as any:

    class Foo {
        private constructor(private x: number) {}
    }
    
    const instance = new (Foo as any)(5) as Foo;
    console.log(instance);
    

    But perhaps you might just want to create a static method that constructs an instance with a clear name that it's for testing:

    class Foo {
        private constructor(private x: number) {}
    
        /** @internal */
        static createForTesting(x: number) {
            return new Foo(x);
        }
    }
    
    const instance = Foo.createForTesting(5);
    

    Note: The /** @internal */ excludes the method declaration from appearing in declaration files.