Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the Closure Compiler to stop complaining about union types when calling a function?

I'm seeing this in particular when using the jQuery-1.4.3 externs file. The javadocs for that reads

/**
 * @param {(string|number|function(number,number))=} arg1
 * @return {(number|jQueryObject)}
 * @nosideeffects
 */
jQueryObject.prototype.width = function(arg1) {};

I have a call that looks like this:

   var w =  $(window).width();
    $('#whatever').width(w)

Closure complains: WARNING - actual parameter 1 of jQueryObject.prototype.height does not match formal parameter found : (jQueryObject|null|number) required: (function (number, number): ?|number|string|undefined) $('#Xobni').height($(window).height());

From playing around (removing the possible return types), I can see that the problem is that the first call to width can return possibly a jQueryObject, and since that's not a valid input, Closure gives me an error. I tried adding this:

/**
 * @type {number}
 */
var w =  $(window).width();
$('#Xobni').width(w);

But then Closure complains: WARNING - initializing variable found : (jQueryObject|null|number) required: number var w = $(window).width();

The problem is that when width takes an argument, it returns a jQueryObject. When it doesn't take an argument, it returns a number. So I know my call is okay, but the javadocs don't quite reflect that, and so Closure is warning me. Is there a way to fix up the javadocs appropriately or a way to tell Closure I know this result will be a number. I know I can probably suppress the error, but I'd like to know how to annotate these things better.

Thanks for the help!

like image 489
Mr. Ubin Avatar asked Oct 28 '10 00:10

Mr. Ubin


2 Answers

You can override this as follows:

var w = /** @type {number} */ ($(window).width());
$('#whatever').width(w)
like image 89
Derek Slager Avatar answered Nov 01 '22 01:11

Derek Slager


Try this:

var w =  $(window).width();
w = parseInt(w.toString());
$('#whatever').width(w);

or this:

var w =  $(window).width() + '';
$('#whatever').width(w);
like image 21
Slappy Avatar answered Nov 01 '22 01:11

Slappy