Typescript conversion to boolean

后端 未结 8 443
名媛妹妹
名媛妹妹 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: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(xxx);
    

    While clumsy, it avoids the type erasure of casting to . It's also arguably less obscure & more readable than the !! approach (certainly so in the transpiled js code).

提交回复
热议问题