I was intrigued by your question and I did some tests to try answering it in the best way possible.
First thing, remember that TypeScript is not JavaScript and it will be ultimately compiled before being ran. Writing private
before declaring the constructor will have no particular effect on compiled code, in other words, not a bit of increased 'security' for doing that.
As @Bergi correctly stated in the comments, generally you can always access a constructor through an instance constructor
property and potentially do const illegalInstance = new legalInstance.constructor();
This last scenario can be avoided by removing constructor
reference completely. Something like:
class MyClass {
constructor() {}
}
delete MyClass.prototype.constructor;
export function myFactory() {
return new MyClass();
}
To more specifically address your concerns, after removing constructor
reference, not exporting your class is sufficient to assume no illegal instances will be created outside of that module. (However, I would never rely on anything in memory for security critical scenarios).
Finally, you could perform some checks inside your constructor, and throw errors if those checks do not pass. This will prevent the class from being instantiated.
I haven't seen other people do it like this
Remember that class
syntax is just syntactic sugar for constructor functions. At the end, the only thing that matters is what ends in the resulting object and its prototype.
Ah! And don't worry about export type {ServiceEndpoint};
, again, this is not JavaScript and will be removed at compile time.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…