Typescript conversion to boolean

后端 未结 8 441
名媛妹妹
名媛妹妹 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条回答
  • 2021-02-02 05:57
    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 ...
      }
    }
    
    0 讨论(0)
  • 2021-02-02 05:59

    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).

    0 讨论(0)
提交回复
热议问题