简体   繁体   中英

Annotation for Google Compiler, @type function with optional parameter

I have searched the google to it's last page and haven't found an answer for this.

How do i annotate a function in the scope of another object which can take as parameters either a string, an array of strings or no parameter at all ?

I tried this:

/**
 * @type function(this:anObject, (string|Array.<string>)=)
 */
deselect = function(val) {
    var temp = val ? ( val instanceof Array ? val : [val]) : [];
    // some code
    this.doSomething(temp);
}.bind(anObject);

But it doesn't work because when i call it without a parameter, the compiler gives back an error like this:

WARNING - assignment
    found   : function (?): undefined
    required: function (this:anObject, (Array.<string>|null|string)=): ?
        deselect = function(val) {

I tend to hate the type checking that Google Closure Compiler works with.

To answer my own question:

To pass the assignment check form the bind return you have to recast the new function as follows:

/**
 * @type function(this:anObject, (string|Array.<string>)=)
 */
deselect = /** @type function(this:anObject, (string|Array.<string>)=) */
(function(val) {
    var temp = val ? ( val instanceof Array ? val : [val]) : [];
    // some code
    this.doSomething(temp);
}.bind(anObject));

If anyone has any idea of how to make this less creepy as it already is, please post it here.

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