Ankur Gupta Ankur Gupta - 1 year ago 188
TypeScript Question

Factory pattern in Typescript and expose only Factory Class

I'm developing a node module in typescript using factory pattern where I want to expose only factory class and interface.



export interface IExp {


class A implements IExp {


class B implements IExp {


export class ExpFactory {
createInstance(type:string) : IExp{
if(type=="A") return new A();
else return new B();

All classes and interface are in their own source file. I do not want to expose class A and class B, so I did not use export but then I'm not able to use them in ExpFactory class either. In Java, classes can have package scope, but how can I do same thing in typescript?

Answer Source

You can use A and B from ExpFactory if they're in the same file. If not, then you must export them from the module, which is all or nothing (it can only be public).

However, that doesn't make them easily accessible from outside your module. If you're bundling your library, the entry point will have to export the classes again, or they won't be accessible outside your module. If you aren't bundling, users would have to figure out the relative path and import directly from that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download