0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is only a small part of the outputted file. Guess what, the line above contains: //# sourceMappingURL=somefilename.js.mapvar ColorType;, The build script concatenates a couple of files into one output file and the var ColorType ends up at the end of the comment of the previous file due to a lack of a carriage return. So, easy fix, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.