Typescript conversion to boolean

后端 未结 8 592
名媛妹妹
名媛妹妹 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 ...
      }
    }
    

提交回复
热议问题