??
??
表示空值合并运算符(Nullish Coalescing),当进行运算的变量为undefined
或null
,赋予变量一个默认的值。
??
在某些场景下可以替换||
。
??
其实可以看做是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 likeif (!!user.isAdministrator)
to indicate that the coercion is intentional.
如果函数定义中不包含undefined/null
,if
判断时会因为函数是defined
而返回true。!!
可以实现强制调用函数,然后对函数返回的结果进行条件判断。