由Typescript枚举生成的javascript中的错误

时间:2016-03-15 17:05:45

标签: typescript typescript1.7

我在Typescript中定义了以下枚举:

override init(layer: Any) {
    super.init(layer: layer)
}

这将编译为以下javascript:

enum ColorType {
    None = 0,
    Default = 1,
    RGB = 2,
    ColorSet = 3,
    Custom = 4
}

这看起来正确且与Tristate enum in the documentation类似。但是,当我在浏览器中运行代码时,Firefox和Chrome都会抱怨{1}未在枚举定义的最后一行定义(function (ColorType) { ColorType[ColorType["None"] = 0] = "None"; ColorType[ColorType["Default"] = 1] = "Default"; ColorType[ColorType["RGB"] = 2] = "RGB"; ColorType[ColorType["ColorSet"] = 3] = "ColorSet"; ColorType[ColorType["Custom"] = 4] = "Custom"; })(ColorType || (ColorType = {})); (即ColorType)。我认为这是第一个。当我手动编辑代码时:

(ColorType || (ColorType = {}))

它在Firefox和Chrome中都能正常运行。

我不明白为什么由Typescript生成的代码会生成错误,看起来他们试图传入已存在的(function (ColorType) { ColorType[ColorType["None"] = 0] = "None"; ColorType[ColorType["Default"] = 1] = "Default"; ColorType[ColorType["RGB"] = 2] = "RGB"; ColorType[ColorType["ColorSet"] = 3] = "ColorSet"; ColorType[ColorType["Custom"] = 4] = "Custom"; })(ColorType = {}); 变量或者创建一个空对象(如果它不存在)。但如果它错了,这是Typescript编译器中的错误吗?我正在使用TSC 1.7.40.24720。

1 个答案:

答案 0 :(得分:1)

听起来你只是剪切并粘贴输出的部分

编译器为枚举生成此代码:

var ColorType; // <---- this is the line you're missing
(function (ColorType) {
    ColorType[ColorType["None"] = 0] = "None";
    ColorType[ColorType["Default"] = 1] = "Default";
    ColorType[ColorType["RGB"] = 2] = "RGB";
    ColorType[ColorType["ColorSet"] = 3] = "ColorSet";
    ColorType[ColorType["Custom"] = 4] = "Custom";
})(ColorType || (ColorType = {}));

如果你跳过var,就会出现你所描述的错误。