有没有办法在输出中组合名称空间?

时间:2016-07-12 00:00:03

标签: typescript

我只是想尝试一下TypeScript,我想把我的代码分成多个文件。我已经looking at the documentation,我找到了我认为我正在寻找名称空间的内容。我正在使用此处文档中的示例:

Validation.ts:

namespace Validation {
    export interface StringValidator {
        isAcceptable(s: string): boolean;
    }
}

LettersOnlyValidator.ts:

/// <reference path="Validation.ts" />
namespace Validation {
    const lettersRegexp = /^[A-Za-z]+$/;
    export class LettersOnlyValidator implements StringValidator {
        isAcceptable(s: string) {
            return lettersRegexp.test(s);
        }
    }
}

ZipCodeValidator.ts:

/// <reference path="Validation.ts" />
namespace Validation {
    const numberRegexp = /^[0-9]+$/;
    export class ZipCodeValidator implements StringValidator {
        isAcceptable(s: string) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
}

我按照示例使用tsc输出到单个文件。 TypeScript生成:

var Validation;
(function (Validation) {
    var lettersRegexp = /^[A-Za-z]+$/;
    var LettersOnlyValidator = (function () {
        function LettersOnlyValidator() {
        }
        LettersOnlyValidator.prototype.isAcceptable = function (s) {
            return lettersRegexp.test(s);
        };
        return LettersOnlyValidator;
    }());
    Validation.LettersOnlyValidator = LettersOnlyValidator;
})(Validation || (Validation = {}));
var Validation;
(function (Validation) {
    var numberRegexp = /^[0-9]+$/;
    var ZipCodeValidator = (function () {
        function ZipCodeValidator() {
        }
        ZipCodeValidator.prototype.isAcceptable = function (s) {
            return s.length === 5 && numberRegexp.test(s);
        };
        return ZipCodeValidator;
    }());
    Validation.ZipCodeValidator = ZipCodeValidator;
})(Validation || (Validation = {}));
var strings = ["Hello", "98052", "101"];
var validators = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
validators["Letters only"] = new Validation.LettersOnlyValidator();
for (var _i = 0, strings_1 = strings; _i < strings_1.length; _i++) {
    var s = strings_1[_i];
    for (var name_1 in validators) {
        console.log("\"" + s + "\" " + (validators[name_1].isAcceptable(s) ? " matches " : " does not match ") + name_1);
    }
}

这很有效,但很难看。有没有办法让它将这两个块合并为一个?

1 个答案:

答案 0 :(得分:1)

  

。有没有办法让它将这两个块组合成一个

不。 TypeScript试图不确定您的JavaScript将如何执行,例如使用--out它不会对文件进行任何特殊排序。

更多

https://basarat.gitbooks.io/typescript/content/docs/tips/outFile.html