如果我在两个不同的命名空间中有两个类型的文件。生成的订单很重要。
export module Shapes {
export module Weird{
export class weirdshape extends Normal.normalshape{
public x = 3;
}
}
export module Normal{
export class normalshape {
public y = 4;
}
}
}
这将生成
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
define(["require", "exports"], function(require, exports) {
(function (Shapes) {
(function (Weird) {
var weirdshape = (function (_super) {
__extends(weirdshape, _super);
function weirdshape() {
_super.apply(this, arguments);
this.x = 3;
}
return weirdshape;
})(Normal.normalshape);
Weird.weirdshape = weirdshape;
})(Shapes.Weird || (Shapes.Weird = {}));
var Weird = Shapes.Weird;
(function (Normal) {
var normalshape = (function () {
function normalshape() {
this.y = 4;
}
return normalshape;
})();
Normal.normalshape = normalshape;
})(Shapes.Normal || (Shapes.Normal = {}));
var Normal = Shapes.Normal;
})(exports.Shapes || (exports.Shapes = {}));
var Shapes = exports.Shapes;
});
按此顺序,这将失败。因为Shapes.Normal.normalshape尚未定义。
在typescript中是否有正确的方法可以将模块用作正确的命名空间?
答案 0 :(得分:1)
因此,如果问题是“如何运行此代码”,答案就是:
export module Shapes {
export module Normal{
export class normalshape {
public y = 4;
}
}
export module Weird{
export class weirdshape extends Normal.normalshape{
public x = 3;
}
}
}
这不是TypeScript的限制 - 它是JavaScript的限制。如果在声明之前使用了某些东西,就会出现问题。
你可能会争辩说TypeScript应该为你排序,因为它可以解决依赖关系。实际上,如果您有单独的文件,它将执行此操作。例如,如果Normal
位于Normal.ts
且Weird
位于Weird.ts
,则生成的输出将为您正确排序。
完整示例:
Weird.ts
/// <reference path="Normal.ts" />
module Shapes {
export module Weird {
export class weirdshape extends Shapes.Normal.normalshape {
public x = 3;
}
}
}
Normal.ts
module Shapes {
export module Normal {
export class normalshape {
public y = 4;
}
}
}
app.ts
/// <reference path="Weird.ts" />
/// <reference path="Normal.ts" />
var weird = new Shapes.Weird.weirdshape();
使用--out final.js
进行编译 - 生成final.js
:
var Shapes;
(function (Shapes) {
(function (Normal) {
var normalshape = (function () {
function normalshape() {
this.y = 4;
}
return normalshape;
})();
Normal.normalshape = normalshape;
})(Shapes.Normal || (Shapes.Normal = {}));
var Normal = Shapes.Normal;
})(Shapes || (Shapes = {}));
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Shapes;
(function (Shapes) {
(function (Weird) {
var weirdshape = (function (_super) {
__extends(weirdshape, _super);
function weirdshape() {
_super.apply(this, arguments);
this.x = 3;
}
return weirdshape;
})(Shapes.Normal.normalshape);
Weird.weirdshape = weirdshape;
})(Shapes.Weird || (Shapes.Weird = {}));
var Weird = Shapes.Weird;
})(Shapes || (Shapes = {}));
var weird = new Shapes.Weird.weirdshape();