TypeScript里的空值合并运算符(双问号)用法

1,904 阅读1分钟

当左侧操作数为 null 或 undefined 时,其返回右侧的操作数,否则返回左侧的操作数。

例子:

const foo = null ?? 'default string';

编译后的JavaScript代码:

var _a;
var foo = (_a = null) !== null && _a !== void 0 ? _a : 'default string';

可见,这个例子,foo必定为default string, 因为编译后的JavaScript代码里,已经能看到null被显式地赋给_a了。

空值合并运算符的短路用法:当空值合并运算符的左表达式不为 null 或 undefined 时,不会对右表达式进行求值。

看个例子:

function A() { console.log('A was called'); return false;}

function B() { console.log('B was called'); return false;}

console.log(A() ?? B());

生成的JavaScript代码:

var _a;
function A() { console.log('A was called'); return false; }
function B() { console.log('B was called'); return false; }
console.log((_a = A()) !== null && _a !== void 0 ? _a : B());

执行JavaScript,可见,??右边的B表达式根本就没有进行求值。

在这里插入图片描述