Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

typescript - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...