title: Typescript/NodeJS - Circular Dependency while working with factories
body: <p>I am quite new to Typescript and NodeJS, I am trying to use a factory to create objects on runtime.</p>
  
  <p>As an example, the following object has property type Text, now getting that in runtime, I would like to create an instance of TextContainer:</p>
  
  <pre><code>{
  type: "Text", 
  name: "Title"
  }
  </code></pre>
  
  <p>My factory looks like this:</p>
  
  <pre><code>import {BaseContainer} from "../Containers/BaseContainer";
  import {TextContainer} from "../Containers/TextContainer";
  /**
   * Used to dynamically create objects with different container classes
   * in runtime
   */
  export class ContainerFactory {
  
      // Object containing all class names and types
      private dictionary: Object;
  
      /**
       * Initializes factory dictionary
       */
      constructor() {
          // Initialize dictionary with classes
          this.dictionary = {
              "default": BaseContainer,
              "Text": TextContainer,
              "TextContainer": TextContainer
          }
      }
  
      /**
       * Builds object depending on className
       * @param className
       * @param params
       */
      build(className: string, params: Object) {
          // Return new class of type className, if not found
          // return object with class of set default class
          return className in this.dictionary ? new this.dictionary[className](params) : new this.dictionary['default'];
  
      }
  }
  </code></pre>
  
  <p>The problem comes in when in BaseContainer class (which is extended by TextContainer and will be extended by many more classes that will be present in this factory) I use the factory in a function, and here comes the circular dependency, because in BaseContainer I import ContainerFactory and in ContainerFactory BaseContainer is imported.</p>
  
  <p>I need the factory in BaseContainer because I have a tree-like hierarchy and the containers have children, which are containers themselves.</p>
  
  <p>I'd appreciate suggestions on how to work around this issue, or how to refractor my code in order for it to work reliably.
  I searched for similar issues but didn't find a workaround yet.</p>
  
  <p>I receive the following error in the TextContainer class (extends BaseContainer):</p>
  
  <pre><code>extendStatics(d, b);
          ^
  
  TypeError: Object prototype may only be an Object or null: undefined
  </code></pre>