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。!!可以实现强制调用函数,然后对函数返回的结果进行条件判断。

你可能感兴趣的:(后端,typescript,javascript,前端)