在 TypeScript 中使用 `??` 来解决默认赋值的场景
2020-05-04 本文已影响0人
Asuna_随便记录点
let x = foo ?? bar();
等价于下面
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
是用来解决以前的类似问题:
function initializeAudio() {
let volume = localStorage.volume || 0.5
// ...
}
When localStorage.volume is set to 0, the page will set the volume to 0.5 which is unintended. ?? avoids some unintended behavior from 0, NaN and "" being treated as falsy values.
完整参考: https://www.typescriptlang.org/docs/handbook/release-notes/overview.html#nullish-coalescing