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
if(xxx) {...} //read as TRUE if xxx is NOT undefined or null if(!xxx) {...} //read as TRUE if xxx IS undefined or null
For a string like 'true' or 'false': xxx.toLowerCase().trim() === 'true' ? true : false
so:
var zzz = 'true'; //string
var yyy = []; //array
...
if(zzz.toLowerCase().trim() === 'true') { ... } // quick string conversion
...
if(yyy ? true : false) { ... } // quick any conversion - it's TRUE if it's not null or undefined
...
// in a catch-all function
if(toBoolean(zzz)) { ... }
if(toBoolean(yyy)) { ... }
toBoolean(xxx: any): boolean {
if(xxx) {
const xStr = xxx.toString().toLowerCase().trim();
if(xStr === 'true' || x === 'false') {
return xStr === 'true' ? true : false;
} else {
return xxx ? true : false;
}
} else {
return false;
}
}