TypeScript: Circular dependency

Looks like I have a circular dependency between three classes (‘->’ means ‘references’): A -> B -> C -> A.

Class A:

import B = require('services/B');

class A
{
    run()
    {
        B.run();
    }
}

export = A;

Class B:

import C = require('services/C');

class B
{
    run()
    {
        C.run();
    }
}

export = B;

Class C:

import A = require('services/A');

class C
{
    run()
    {
        A.run();
    }
}

export = C;

Whenever I try to execute C.run in B I get exception: “TypeError: C.run is not a function” and in debug mode C is nothing, but an empty object.

Ok, I can redesign my classes to break the chain, but is it possible to have such references in TypeScript and what do I need to do?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 17 (5 by maintainers)

Most upvoted comments

Why is this issue closed when no answer to these issues has been posted???

I’ve been stuck with the same problem in Node JS for days now. I need to reference type A from B, and B from A. In pure JS, I would use runtime require and place “module.exports” at the beginning of the file, so Node can fill in the missing references later, as it resolves them. However, in Typescript I have no control over how and where “module.exports” is generated, so it always overwrites the whole object, causing unresolved modules. So what is the official workaround for Typescript files??

Not creating circular dependencies at all is NOT an option when models refer to each other (think foreign keys in a database).

stupid question… are these functions instance or static?

also what module loader are you using?

@Spongeman haven’t looked much into it, but these tslint-rules might help you.