typescripttypescript1.7

Error in javascript generated by Typescript enum


I've defined the following enum in Typescript:

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

This compiles down to the following javascript:

(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 = {}));

This looks correct and similar to the Tristate enum in the documentation. However when I run the code in the browser, both Firefox and Chrome complain about ColorType being not defined on the last line of the enum definition (i.e. (ColorType || (ColorType = {}))). I think it's specifically the first one. When I manually edit the code to:

(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 = {});

it works fine in both Firefox and Chrome.

I don't understand why the code generated by Typescript generates the error, it looks like they are trying to either pass in an already existing ColorType variable or create an empty object if it doesn't exist. But if it's wrong, is this an error in the Typescript compiler? I'm using TSC 1.7.40.24720.


Solution

  • It sounds like you're just cutting and pasting part of the output?

    The compiler generates this code for an enum:

    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 = {}));
    

    If you skip the var, you're going to get errors like you describe.