Search code examples
javascriptannotationsgoogle-closure-compilerjsdoc

Google Closure Compiler @param annotation for variable parameters


I have a function that can accept a variable number of parameters.

According to Google Closure Compiler wiki, this is the way to do it using @param annotation.

/**
 * 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');
    }

    ...
}

Problem

When I try compiling it, I see this warning: JSC_INEXISTENT_PARAM: parameter var_args does not appear in doSomethingCool's parameter list at line 6 character 1

So I tried @param {string} arguments, but same error.

I also tried @param {string} with no variable name. I got: JSC_TYPE_PARSE_ERROR: Bad type annotation. expecting a variable name in a @param tag.

Question

What did I do wrong and how can variable parameters be annotated for Closure Compiler?


Solution

  • Your var_args needs to actually appear in the parameter list which is what the error is telling you.

    /**
     * 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 will recognize that it's never referenced and remove it during compilation.

    If having it listed there bothers you, you can use an @type annotation instead:

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

    If you really want correct type checking, annotate the function so that it takes 2 or more strings:

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