TypeScript modules

Rob*_*sen 12 module typescript

I am wondering if it is possible somehow to have two or more classes in two or more files added to the same module in TypeScript. Something like this:

//src/gui/uielement.ts
module mylib {
    module gui {
        export interface UIElement {
            public draw() : void;
        }
    }
}

//src/gui/button.ts
///<reference path='uielement.ts'/>
module mylib {
    module gui {
        export class Button implements UIElement {
            constructor(public str : string) { }
            draw() : void { }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

There will probably be dozens of GUI classes, so having them all in the same file will not be possible. And all my classes will be in the 'mylib' module. But how do I do that?

如果将module mylib {...}其转换为函数,则所有文件中所有mylib块的所有内容都应包含在同一函数中.

这是可能吗?

当我编译时,我得到这个:

$ tsc src/gui/button.ts 
src/gui/button.ts(4,39): The name 'UIElement' does not exist in the current scope
Run Code Online (Sandbox Code Playgroud)

Phi*_*ayr 22

这正是它的工作原理!如果你看一下生成的javascript代码,它会添加一个接受一个对象的匿名函数,即"模块对象":

var mylib;
(function (mylib) {
    var Button = (function () {
        function Button(x) {
            this.x = x;
        }
        return Button;
    })();
    mylib.Button = Button;    
})(mylib || (mylib = {}));
Run Code Online (Sandbox Code Playgroud)

如果查看最后一行(})(mylib || (mylib = {}));),mylib = {}只有当现有变量为false(或者计算结果为false,如null)时,才会看到它实例化一个新的ojbect().这样,所有命名相同的"模块"将合并到同一个对象.

因此,内部模块相互扩展.我必须指出,我还没有弄清楚嵌套模块会发生什么.

更新:如果我不使用嵌套模块语法,但您的代码适用于我,但将其更改为点语法.例如:

module mylib.gui {
}
Run Code Online (Sandbox Code Playgroud)

代替

module mylib {
    module gui {
    }
}
Run Code Online (Sandbox Code Playgroud)

我将尝试调查为什么会发生这种情况,只要我阅读规范,两种方式应该是平等的.

更新:如果嵌套的引用模块标记为已导出,则它有效:

module mylib {
    export module gui {
    }
}
Run Code Online (Sandbox Code Playgroud)