typescriptでstatic memberにobjectを格納しようとした時定義順序を意識しないと実行時エラーになる場合がある。

typescriptでstatic memberにobjectを格納しようとした時定義順序を意識しないと実行時エラーになる場合がある。

例えば以下のようなコード。

class X {
  static y: Y = new Y();
  say() {
    return X.y.say();
  }
}

class Y {
  say() {
    console.log("hai");
  }
}

これは以下の様なコードを出力する。(--target=es5)

var X = (function () {
    function X() {
    }
    X.prototype.say = function () {
        return X.y.say();
    };
    X.y = new Y();
    return X;
})();
var Y = (function () {
    function Y() {
    }
    Y.prototype.say = function () {
        console.log("hai");
    };
    return Y;
})();

Xのクラス定義に対応する即時関数の実行でnew Yが呼ばれるもののYの定義はその後なのでエラーになる。