Order of class definitions - any way to circumvent?

时间:2016-04-15 11:07:13

标签: typescript

I am discovering that TypeScript does not give an error when I try to create a new instance of class B inside of class A.

class A {
    public static foo = new B();
}

class B { }

Calling A.foo after these definitions would obviously fail since B is not lexically before A. Removing static is not an option (because I do not want to).

So, is my only option to do the reordering of the class definitions manually, or are there any tricks I can do to circumvent this? Would a module loader help me here, or do I still need to explicitly define the depencency order?

1 个答案:

答案 0 :(得分:2)

你的打字稿代码

class A {
    public static foo = new B();
}

class B { }

转换为以下JavaScript:

var A = (function () {
    function A() {
    }
    A.foo = new B();
    return A;
}());
var B = (function () {
    function B() {
    }
    return B;
}());

JavaScript因此处理文件,并在

    A.foo = new B();

" B"是未定义的,因为尚未解析JS。

这可以通过以下方式解决:

1)重新排序文件中的类声明

2)提取" B"将类代码分成单独的文件并使用

引用A文件

2.1)/// <reference path="B.ts" />

这应该添加在A.ts文件的顶部, 这将明确定义依赖顺序

2.2)或使用require(import)指令和模块化构建

更新1

变式2.1:

a.ts

/// <reference path="b.ts" />
class A {
    public static foo = new B();
}

b.ts

export class B { }

变体2.2(我没有完全测试过这段代码,但认为它有效):

a.ts

import { B } from "./b";

class A {
    public static foo = new B();
}

export { A };

b.ts

class B { }

export { B };