2022-3 | TypeScript运算符

??

??表示空值合并运算符(Nullish Coalescing),当进行运算的变量为undefinednull,赋予变量一个默认的值。

??在某些场景下可以替换||

??其实可以看做是if(条件表达式){代码}的简写,替换后为条件表达式 ?? 代码

// ||运算符处理0, NaN, ""等情况会返回false
const a = 0;
const result = a || true;
console.log(`result: ${result}`); // result: true

// ??运算符避免这种情况
const b = 0;
const result = b || true;
console.log(`result: ${result}`); // result: 0

!!

TypeScript官方手册未调用函数检查中的一段描述:

If you intended to test the function without calling it, you can correct the definition of it to include undefined/null, or use !! to write something like if (!!user.isAdministrator) to indicate that the coercion is intentional.

如果函数定义中不包含undefined/nullif判断时会因为函数是defined而返回true。!!可以实现强制调用函数,然后对函数返回的结果进行条件判断。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值