Typescript conversion to boolean

后端 未结 8 444
名媛妹妹
名媛妹妹 2021-02-02 05:19

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

8条回答
  •  梦毁少年i
    2021-02-02 05:41

    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!'
    

提交回复
热议问题