Is there a way to use an enum as type in Google Closure Compiler?

google-closure-compiler, javascript

Solution

Aliasing types using a function parameter is not well supported in Closure-compiler. Use the `--output_wrapper` flag to enclosure your code after compilation. The following code compiles correctly:

/** @const */
var MyNamespace = window.MyNamespace || {};

/** @enum {number} */
MyNamespace.MyEnum = {
  FOO: 1,
  BAR: 2,
  BAZ: 3
};
/**
 * @constructor
 * @param {Object} foo
 */
MyNamespace.MyClass = function (foo) {
  this.foo = foo
};
/**
 * @constructor
 * @param {MyNamespace.MyClass} bar
 */
MyNamespace.MyOtherClass = function (bar) {
  this.bar = bar
};
/** @param {MyNamespace.MyEnum} baz */
MyNamespace.MyOtherClass.prototype.someMethod = function (baz) {};

Problem

I tried doing something like `@param {window.MyNamespace.MyEnum} myVar`, but the compiler complained about a `JSC_TYPE_PARSE_ERROR: Bad type annotation. Unknown type window.MyNamespace.MyEnum`. Should I have done an `@typedef`on the enum, or just use `@param {number}`, if my enum is `@enum {number}`? I really prefer the enum thing, as other values aren't really allowed. ``` (function (MyNamespace) { /** * @enum {number} */ MyNamespace.MyEnum = { FOO: 1, BAR: 2, BAZ: 3 } /** * @constructor * @param {Object} foo */ MyNamespace.MyClass = function (foo) { this.foo = foo } /** * @constructor * @param {MyNamespace.MyClass} bar */ MyNamespace.MyOtherClass = function (bar) { this.bar = bar } /** * @param {MyNamespace.MyEnum} baz */ MyNamespace.MyOtherClass.prototype.someMethod = function (baz) { } })(window.MyNamespace = window.MyNamespace || {}) ```

Original source