javascript - Closure Compiler: Avoid "missing return statement" warning when a return is guaranteed -


this function return "foobar":

/**  * @return {string}  */ function foobar() {      var x = true;      if (x) {         return 'foobar';     }  } 

when compiled command:

java -jar compiler-20150609.jar --js test.js --warning_level verbose 

this warning raised:

test.js:4: warning - missing return statement. function expected return string. function foobar() { ^ 

similarly, function return string:

/**  * @param  {boolean} bool  * @return {string}  */ function convertbooltostring(bool) {      var boolstring = bool ? 'true' : 'false';      switch (boolstring) {         case 'true':             return 'yes';         case 'false':             return 'no';     }  } 

again, compiler raises warning "missing return statement. function expected return string."

i know warnings can suppressed adding @suppress {missingreturn}, i'd know if there's better solution. there "hint" can provided compiler's flow analysis? maybe similar type cast (which useful in cases type-checking doesn't accurately infer type of expression) ?


update

i should have made clearer i'm looking solution only involves "hinting" compiler. example: using suitable jsdoc tag or supplying particular cli flag compiler alter flow analysis.

i'm not looking solution involves modifying js source code "keep compiler happy".

the disadvantage of @chsdk's solution return variable must initialised dummy value of correct type. if return type class instance, dummy instance has created, , constructor may require parameters must given dummy values. in opinion, code smell: dummy value of return variable never used, , it's workaround unrelated problem (a compiler warning).

i'm looking solution this:

/**  * @return {string}  */ function foobar() {      var x = true;      /** @alwaysreturns */     if (x) {         return 'foobar';     }  } 

does compiler support jsdoc tag such @alwaysreturns, or other similar "hinting" mechanism flow analysis? maybe cli flag?

closure compiler not have "hint" mechanism modify control flow analysis. stuck disabling warning group altogether, @suppress annotations or modifying code.


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -