使用TypeScript中的扩展类进行交叉引用

时间:2013-01-04 11:35:47

标签: typescript

我发现了一个奇怪的错误。

如果您在不同的文件中有两个类,例如类 B 扩展类 A ,而类 A 具有变量类型< strong> B ,TypeScript使用--out main.js命令以错误的顺序编译(当您将整个项目编译成一个文件时)。 错误的订单导致javascript抛出错误:未捕获的TypeError:无法读取未定义的属性'prototype' 这是因为类 B 在代码中比 A 更早,并且它想要使用它。

这是最简单的例子:

A.ts

///<reference path='B.ts'/>

class A
{
    public b: B;

    constructor()
    {
    }

    init()
    {
        this.b=new B();
    }
}

B.ts

///<reference path='A.ts'/>
class B extends A
{
    constructor()
    {
        super();
    }
}

app.ts

///<reference path='A.ts'/>
var a: A=new A();
a.init();

生成的main.js

var __extends = this.__extends || function (d, b) {
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var B = (function (_super) {
    __extends(B, _super);
    function B() {
        _super.call(this);
    }
    return B;
})(A);
var A = (function () {
    function A() {
    }
    A.prototype.init = function () {
        this.b = new B();
    };
    return A;
})();
var a = new A();
a.init();
//@ sourceMappingURL=main.js.map

有解决方法吗?

2 个答案:

答案 0 :(得分:0)

我不确定你的循环依赖。如果你想替换类,那么依赖关系应该是一个方向。这是一个例子:

class A {
    constructor(public b: A)
    {
    }
}

class B extends A
{
    constructor()
    {
        super(this);
    }
}

var a = new A(new B());
var b = new B();

现在你的“b.ts”文件只需要依赖于“a.ts”文件 - 而不是相反。因为B扩展了A,所以在创建新的A时可以传入B的实例。因为依赖是单向的,所以TypeScript现在有可能以正确的顺序编译事物。

Here is a picture to show the dependency issue:enter image description here

答案 1 :(得分:0)

在声明的typescript模块或类或接口上使用export语句,然后您可以import所需的函数,类或其他。 Typescript抛出错误,因为您尝试引用的变量不存在。

例如:

module API {
    export class Main {
        public name: string;
        public interest: string;

        constructor() {
            this.name = "Someone";
            this.interest = "web technology";
        }

        puts() {
            console.log(this.name, " like", this.interest);
        }
    }
}

..然后你可以调用所需的功能。

import API;
var c = new API.Main();