Class 'X' used before its declaration

Viewed 430

I have 2 classes X and Y. for some reason the 2 classes are at the same file as follow:

export abstract class Y {
  static readonly childVar = new X();
}

export class X extends Y {

}

An error occurs when creating this new object says class X is used before its declaration. Any solutions?

1 Answers

This kind of circular reference is usually bad design and I would prefer to recommend an alternative but I would have to see more of your code. If you really must do this, then you can defer the construction with a getter:

export abstract class Y {
  private static _childVar: Y
  static get childVar () { 
    return this._childVar || (this._childVar = new X())
  }
}

export class X extends Y {

}

This will work as long as you don't try to access childVar before X is defined.

Related