Ankur Gupta Ankur Gupta - 2 months ago 32
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.

Structure:

iexp.ts

export interface IExp {
methodX();
}


A.ts

class A implements IExp {
}


B.ts

class B implements IExp {
}


factory.ts

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

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.

Comments