简体   繁体   中英

Closure-compiler param type Object.<string, *> doesn't works as expected

What would be the correct way to annotate the types of options that I could pass through an object as a function argument? Example:

/**
 * test() function can receive all type of options.
 * @param {Object.<string, *>} options
 * @expose
 */
function test(options) {
    if(typeof options.set !== "undefined") {
        alert(options.set);
    }

    if(typeof options.callback !== "undefined") {
        options.callback.apply(this, []);
    }
}

How I can define something like it ... ?

/**
 * @param {Object.<string, *>} options
 *     @param {Object.<string, *>} options.set
 *     @param {function(... [*])}  options.callback
 */

If I not does nothing, the compiler return an error like:

script.js:28: WARNING - Property callback never defined on Object.<string, *>
                  options.callback.apply(this, []);
                  ^

Usage method:

java -jar "compiler.jar" 
    --compilation_level ADVANCED_OPTIMIZATIONS 
    --warning_level VERBOSE 
    --js "script.js" 
    --js_output_file "script.min.js"

您可以使用记录类型

@param {{set: Object, callback: function}} options

If you want to specify each option exactly you can do it like this:

/**
 * @param {{row: number, field: string, callback: function(string) }} options
 */

So you can declare object structure, including types, details are here .

Just need to create a new variable and set it as a @constructor , @expose ing all this methods, like:

/**
 * @constructor
 */
var TestOptions = function() {
    /**
     * @type {Object.<string, *>}
     * @expose
     */
    this.set;

    /**
     * @type {function(... [*])}
     * @expose
     */
    this.callback;
};

After I just need set this as @param type, like:

/**
 * test() function can receive all type of options.
 * @param {TestOptions} options
 * @expose
 */
function test(options) {
    /* ... */
}

TestOptions will not be on script.min.js because I never used new on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM