在 TypeScript 中使用 `??` 来解决默认赋值的场景

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。