Google Closure Compiler emitting warnings: incompatible types; even when parameters have common types, is there a way to fix that?

StackOverflow https://stackoverflow.com/questions/22903311

Frage

I get many of those warnings:

plugins/editor/editor.js:933: WARNING - actual parameter 2 of jQuery.prototype.attr does not match formal parameter
found   : (Array.<string>|jQuery|null|number|string)
required: (boolean|function (number, string): ?|number|string|undefined)
            jtag.attr("title", title.val());
                               ^

In this case I want to set an attribute using jQuery, and we see that title.val() returns a string type and the attr() second parameter accepts a string. However, I think that the compiler wants all the found types to be compatible with the required types.

In this case I suppose the warning means the Array.<string>, jQuery, and null are missing from the possible input of the attr() function (although null may be fine because the second parameter should be optional).

Is there a way other than editing the jQuery definitions to allow the other types?

I know we can cast the parameter like this:

jtag.attr("title", /** @type {string} */ (title.val()));

but hundred of casts sounds crazy for such "simple" things.

War es hilfreich?

Lösung

If this is common, it is better to use a helper function to assert the correct type using runtime type check, a "type cast" type expression or or similar:

/** 
  @param {whatever} title
  @return {string} 
 */
function getVal(title) {
  var val = title.val();
  if (typeof val != "string") {
    throw Error("expected string");
  }
  return val;
}

Andere Tipps

Google Closure Compiler doesn't work extremely well in such situations. The type checking's role is to prevent silly errors like you passing an Array where a boolean is required. In your case, the compiler has no way to tell if the object you pass is an Array (unacceptable) or a string (acceptable). Since you might feed it an unacceptable value, it will throw a warning.

The solution is as you observed yourself to use a type-cast to inform the compiler about the specific type returned under these particular circumstances.

Other possibilities are to disable type checking or to mark these warnings as known warnings so they don't bother you (through suppression or whitelisting).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top