Google Closure Compiler @param 变量参数注解

Google Closure Compiler @param annotation for variable parameters

我有一个函数可以接受可变数量的参数。

根据 Google Closure Compiler wiki,这是使用 @param 注释的方法。

/**
 * Takes 2 or more strings and do something cool with them.
 * @param {...string} var_args
 * @return {string} the processed result
 */
function doSomethingCool() {
    var len = arguments.length;
    if (len < 2) {
        throw Error('Need at least 2 arguments');
    }

    ...
}

问题

当我尝试编译它时,我看到这个警告:JSC_INEXISTENT_PARAM: parameter var_args does not appear in doSomethingCool's parameter list at line 6 character 1

所以我尝试了 @param {string} arguments,但同样的错误。

我也试过 @param {string} 没有变量名。我得到:JSC_TYPE_PARSE_ERROR: Bad type annotation. expecting a variable name in a @param tag.

问题

我做错了什么,如何为 Closure Compiler 注释变量参数?

您的 var_args 需要实际出现在参数列表中,这就是错误告诉您的内容。

/**
 * Takes 2 or more strings and do something cool with them.
 * @param {...string} var_args
 * @return {string} the processed result
 */
function doSomethingCool(var_args) {}

Closure-compiler 将识别它从未被引用并在编译期间将其删除。

如果将它列在那里让您感到困扰,您可以改用 @type 注释:

/**
 * Takes 2 or more strings and do something cool with them.
 * @type {function(...string):string}
 */
function doSomethingCool() {}

如果您真的想要正确的类型检查,请注释该函数,使其接受 2 个或更多字符串:

/**
 * Takes 2 or more strings and do something cool with them.
 * @type {function(string, string, ...string):string}
 */
function doSomethingCool() {}