Typescript conversion to boolean

后端 未结 8 531
名媛妹妹
名媛妹妹 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:48

    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;
      }
    }
    

提交回复
热议问题