Ankur Gupta
Ankur Gupta

Reputation: 23

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?

Upvotes: 0

Views: 1558

Answers (2)

wkrueger
wkrueger

Reputation: 1373

(Personal style advice) In javascript, factory pattern is better achieved by using closures and option bags.

class Root {
  method1()
  method2()
}

class Child extends Root {
  method1() //...
}

is better achieved by something like

function Root( opts : Options ) {
   var method1 = opts.method1 || defaultMethod1()
   var method2 = opts.method2 || defaultMethod2()
   return { method1, method2 }
}

The use of new is completely unnecessary in javascript, if not even considered harmful.

Upvotes: 0

ssube
ssube

Reputation: 48337

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.

Upvotes: 1

Related Questions