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
With TypeScript 2.0.2 you can do this:
type Falsey = '' | 0 | false | null | undefined;
function eatFruit(fruit: string | Falsey) {
if (fruit) {
alert(`Ate ${fruit}`);
} else {
alert('No fruit to eat!');
}
}
const fruits = ['apple', 'banana', 'pear'];
eatFruit(fruits[0]); // alerts 'Ate apple'
eatFruit(fruits[1]); // alerts 'Ate banana'
eatFruit(fruits[2]); // alerts 'Ate pear'
eatFruit(fruits[3]); // alerts 'No fruit to eat!'
const bestBeforeDay = 12;
let day = 11;
eatFruit(day < bestBeforeDay && 'peach'); // alerts 'Ate peach'
day += 1;
eatFruit(day < bestBeforeDay && 'peach'); // alerts 'No fruit to eat!'
let numMangos = 1;
eatFruit(numMangos && 'mango'); // alerts 'Ate Mango'
numMangos -= 1;
eatFruit(numMangos && 'mango'); // alerts 'No fruit to eat!'