Question

How can I get rid of the warnings on running the following code through Google Closure Compiler Advance mode?

var defaults = {
    team : 'ABC',
    wr:  'Calvin',
    qb: 'Manning'
};

var config = {};

var setters = {
    team : function(){ return defaults.team},
    wr : function(){ return defaults.wr}
};

for(var i in setters){
    config[i] = setters[i].call();
}


alert( config.team);
alert( config.wr);

Number of warnings: 2

JSC_INEXISTENT_PROPERTY: Property team never defined on config at line 19 character 7
alert(config.team);

   ^
 JSC_INEXISTENT_PROPERTY: Property wr never defined on config at line 20 character 7
 alert(config.wr);


   ^
Was it helpful?

Solution

Found it.

@lends does the trick.

lends tag

var defaults = {
    team : 'ABC',
    wr:  'Calvin',
    qb: 'Manning'
};
var config = {};


var setters = 
/** @lends {config} */
{
    team : function(){ return defaults.team},
    wr : function(){ return defaults.wr}
};

for(var i in setters){
    config[i] = setters[i].call();
}


alert(config.team);
alert(config.wr);

OTHER TIPS

I guess you should define these properties with null value, so compiler would know about it.

var config = {
    team: null,
    wr: null
};

And suggestion number 2 (I'm not sure about this): try annotate type of config. Something like this:

/** @type {{team: *, wr: *}} */
var config = {};

OR using clone:

var config = goog.object.clone(setters);
goog.object.forEach(config, function(val, key) {
    config[key] = val.call();
});

As an alternative, you can annotate the type as being more generic:

/** @type {Object} */  var config = {};  // allow any prop defined anywhere on any object.

or more specific:

/** @type {{team:(string|undefined), wr:(string|undefined), qb:(string|undefined)}} */  var config = {};  // "team", "wr" and "qb" are expected.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top