我正在尝试制作类似 Java 枚举的东西。它工作得很好,但是当我尝试用 ClosureCompiler 编译它时,我收到这个警告:
F:\Site\_data\test-ccomp>ccomp -O ADVANCED --js source.js --js_output_file compiled.js
source.js:49:18: WARNING - [JSC_TYPE_MISMATCH] Can only iterate over a (non-null) Iterable type
found : (typeof Color)
required: Iterable
49| for( const clr of Color ) {
^^^^^
0 error(s), 1 warning(s), 87.2% typed
如何摆脱它?使用哪些注解? 如果我使 Color 成为一个对象,而不是一个函数,具有某些 ColorObj 类型的属性 RED、GREEN、BLUE 和 [Symbol.iterator] 来迭代它们,它仍然是相同的警告。
//////////////////
// Color type
//////////////////
/**
* For id generation.
*/
let color_counter = 0;
/**
* @constructor
* @param {string} txt Color name.
*/
function Color(txt) {
const id = color_counter++;
const text = txt;
this.ordinal = function() {
return id;
}
this.name = function() {
return text;
}
}
/**
* @const
* @type {Color}
*/
Color.BLUE = new Color("blue");
/**
* @const
* @type {Color}
*/
Color.RED = new Color("red");
/**
* @const
* @type {Color}
*/
Color.YELLOW = new Color("yellow");
/**
* What to annotate here for warning to go away?!
*/
Color[Symbol.iterator] = function*() {
yield Color.BLUE;
yield Color.RED;
yield Color.YELLOW;
}
///////////////////
// Test program
///////////////////
console.info("Colors:");
for (const clr of Color) {
console.info(" - " + clr.name());
}
console.info("Color.BLUE is " + Color.BLUE.name());
console.info("Color.RED is " + Color.RED.name());