【问题标题】:Google Closure Compiler @param annotation for variable parameters可变参数的 Google Closure Compiler @param 注解
【发布时间】:2018-01-10 11:30:33
【问题描述】:

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

根据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 注释可变参数?

【问题讨论】:

    标签: javascript annotations google-closure-compiler jsdoc


    【解决方案1】:

    您的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() {}
    

    【讨论】:

    • 我实际上希望坚持使用@param 注释以确保所有功能的一致性。看来我别无选择,只能对这些函数使用 @type 注释。
    • 或者,您可以更有效地编写代码。使用arguments 对象通常被认为是不好的做法,因为它会增加该函数的额外开销并阻止某些 JIST 优化。如果您需要将可变数量的东西传递给doSomethingCool,那么只需将可变长度数组作为第一个参数传递doSomethingCool
    猜你喜欢
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 2014-10-15
    • 2011-05-12
    相关资源
    最近更新 更多