Suggestion: Require control structures tests ( if, while, etc ) to evaluate to bool or any

Topics: Language Specification
Oct 29, 2012 at 1:51 AM
Edited Oct 29, 2012 at 1:52 AM


var value = funcThatReturnsBool;

if ( value ) {

	console.log( 'value is true' );



Consider the above TypeScript code.  There is of course a bug in it.  The programmer meant for value to equal the return of funcThatReturnsBool and not the function itself.   Things like this cause headaches especially since for now the program output might be correct.   It would be nice if the compiler could realize that value should be of type bool and not ()=>bool.


If the compiler complained every time a control structure test didn't evaluate to any or bool it would eliminate a lot of these sort of bugs.  You would still be able to test if an object exists by comparing to 'undefined'   What does everyone think?


Oct 29, 2012 at 8:03 AM
Edited Oct 29, 2012 at 8:07 AM

It is common for JavaScript to use if (x) to check if x is null.

Your suggestion would render all such code invalid.


One valid alternative would be to add control flow check, which would warn when an argument of 'if' is statically known to be not-null.


The downside of such feature is that control flow analysis of potentially expensive. But on the upside it will catch that error. 


P. S. Man this editor is quacky when used from mobile browser. 

Oct 29, 2012 at 9:07 PM

So you are forcing the user to write this in other situations:

if (maybe != null && maybe != undefined)

Coffeescript adds an existenial question mark operator, so the above looks like:

if (maybe?)

That would make this suggested change much easier on users. But TypeScript follows the javascript specification and I don't think there is an existential operator planned.

An alternative would be to write your own typed function:

ifBool(value, () => console.log('value is true'))

Of course, this no longer looks like a control structure. So an alternative feature request would be to ask for the ability to create control structures. This also seems outside the goals of TypedScript, but I am hoping that sweet.js can be integrated with TypedScript to accomplish it.