[Typescript] Nullish Coalescing

class Foo {
    #name;
    constructor(rawName?: string) {
        this.#name = rawName ?? (no name)
    }
    log() {
        console.log(this.#name)
    }
}

Checking 'rawName' is nullish or not, if it is then 'this.name' will be (no name) otherwise set value for rawName.

 

Difference bettwen || and ??

'||': if the rawName is empty string, then the final value will be (no name)

'??': previous case won't happen, here we only check nullish value

posted @ 2020-11-14 18:11  Zhentiw  阅读(106)  评论(0编辑  收藏  举报