Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript inheritance and circular dependencies in SystemJS

I'm using TypeScript with --module system (SystemJS) in a very large project. SystemJS supports cyclic dependencies, and most of the time it works fine. However, when TypeScript inheritance gets involved, things begin to break.

For example, if a class A depends on class B, and class B inherits from class A, then if class A gets loaded first:

  1. It will pause class A's resolution and will try to load the class B dependency
  2. class B will think its dependencies are resolved, since class A has been touched.
  3. class B's inheritance will fail to resolve, because class A is still undefined.

Most of the "solutions" I can find on the web to circular dependencies with module loaders are either:

  • Change your design / combine classes into a single module
  • CommonJS and non-TypeScript specific workarounds

I feel like there are valid justifications for circular designs, and combining classes into giant files is not always desirable, so please consider these workarounds to be off topic for the question that I am asking.

Are there any solutions to the actual problem?

like image 273
Eric Avatar asked Mar 13 '23 06:03

Eric


1 Answers

Changing your design is the most favourable solution. A class should not depend on its subclasses. If you use them in a factory or so, that is a separate concern and should go in a separate class/function/module.

Are there any solutions to the actual problem?

As you said, the problem occurs only when module A is loaded first. The solution is to prevent that, and write an extra module that acts as a proxy to A and all its subclasses while importing them in the correct order.

like image 171
Bergi Avatar answered Mar 15 '23 10:03

Bergi