Search code examples
javascriptgoogle-closure-compiler

How to annotate nested object in javascript for Closure Compiler and have all properties optional?


Here is my class A and I want all options to be optional. It works fine for a,b,c properties but it doesn't work for c.cX properties. How to do it properly to make all properties optional?

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==

/**
 * @typedef {{
 *     a: (string|undefined),
 *     b: (number|undefined),
 *     c: ({
 *         ca: (string|undefined),
 *         cb: (number|undefined),
 *         cc: (Function|undefined)
 *     }|undefined)
 * }}
 */
var Options;


/**
 * @param {Options=} options
 * @constructor
 */
var A = function(options) {
    console.log(this);
};


new A({
    a: 'x',
    c: {
        ca: 'x',
        //cb: 1,
        cc: function() {}
    }
});

Solution

  • Options type should be defined like this:

    /**
     * @record
     * @struct
     */
    function Options() {};
    
    /** @type {string|undefined} */
    Options.prototype.a;
    
    /** @type {number|undefined} */
    Options.prototype.b;
    
    /** @type {!OptionsC|undefined} */
    Options.prototype.c;
    
    
    /**
     * @record
     * @struct
     */
    function OptionsC() {};
    
    /** @type {string|undefined} */
    OptionsC.prototype.ca;
    
    /** @type {number|undefined} */
    OptionsC.prototype.cb;
    
    /** @type {Function|undefined} */
    OptionsC.prototype.cc;