In Typescript I can do this:
var xxx : some_type;
if (xxx)
foo();
else
bar();
Here xxx will be treated as a boolean, regardless of its
foo(!!xxx); // This is the common way of coercing variable to booleans.
// Or less pretty
foo(xxx && true); // Same as foo(xxx || false)
However, you will probably end up duplicating the double bang everytime you invoke foo
in your code, so a better solution is to move the coerce to boolean inside the function DRY
foo(xxx);
foo(b: any){
const _b = !!b;
// Do foo with _b ...
}
/*** OR ***/
foo(b: any){
if(b){
// Do foo ...
}
}
While you can't cast a number directly to a boolean, you can cast it to the wrapper Boolean class and immediately unwrap it. For example:
foo(<boolean><Boolean>xxx);
While clumsy, it avoids the type erasure of casting to <any>
. It's also arguably less obscure & more readable than the !!
approach (certainly so in the transpiled js code).