Welcome to OGeek Q&A 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...