Sunder Sunder - 1 month ago 12
TypeScript Question

Circular dependency with Angular 2 and SystemJS

I have a problem that I think is caused by a circular dependency. After some extensive research, I haven't been able to find a solution. It looks related to this issue : TypeError: b is undefined in __extends in TypeScript, but it didn't help me.

I have been able to simplify the problem in this plunker.

Basically there are 3 classes :


  • the class
    A
    , that contains an array of
    A

  • the class
    B
    , that inherits from
    A

  • the class
    F
    , a factory that can create an
    A
    or a
    B
    depending on a value



The purpose of this is to handle a parameter list that can be dynamic (each
A
is a parameter and can be an array) and where
B
is a specialization of
A
to handle files. I tried removing the factory, but with only
A
and
B
I still get the same error :

TypeError: b is undefined
Error loading http://localhost:3000/app/main.js


Here is the code of a.ts

import { F } from './f';

export class A {
children: A[]

constructor(hasChildren: boolean = false) {
if (hasChildren) {
for (var i = 0 ; i < 10 ; ++i) {
let isB = (Math.random() * 2) > 1;
this.children.push(F.createObject(isB))
}
}
}
}


b.ts

import { A } from './a';

export class B extends A {
}


and f.ts

import { A } from './a'
import { B } from './b'

export class F {
static createObject(isB: boolean): A {
if (isB) {
return new B
} else {
return new A
}
}
}

Answer

You can't have a circular dependency this way. You can work around by using an interface

Plunker example

tata.ts

import { IToto } from './itoto';


export class Tata implements IToto {
  children: Toto[]
}

toto.ts

import { Tata } from './tata';
import { IToto } from './itoto';

export class Toto implements IToto{
  children: Toto[] = [];

  constructor(hasChildren: boolean = false) {
     ...
  }
}

itoto.ts

import { IToto } from './itoto';


export class Tata implements IToto {
  children: Toto[]
}