[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

原文地址:https://www.cnblogs.com/Answer1215/p/13974194.html