liveBook · Manning

Nullish coalescing operator

As explained in Essential TypeScript 5, Third Edition

The nullish coalescing operator returns its right-hand operand only when its left-hand operand is null or undefined.

Use `??` when a fallback should replace only `null` or `undefined`. Unlike logical OR (`||`), it preserves other falsy values, including `0`, `false`, and the empty string. section 3.3.2

Keep a zero tax rate

In `primer/index.js`, `let taxRate;` makes `taxRate ?? 10` produce `10`. After `taxRate = 0`, the same expression produces `0`. Using `taxRate || 10` would produce `10` in both cases, incorrectly replacing the legitimate zero rate. section 3.3.2

The operator also supplies defaults for missing object properties: `hat.price ?? 0` handles an absent price, but assumes `hat` itself exists. Use `hat?.price ?? 0` when the object might also be `null` or `undefined`; optional chaining prevents the property read, and `??` supplies the fallback. section 3.5.1

Listing 11.32 Using a fallback value in the index.ts file in the src folder
interface Product { 
    name: string;
    price: number;
}

class SportsProduct implements Product {
    constructor(public name: string, public category: string, 
            public price: number) {
        // no statements required
    }
}

class ProductGroup {
    constructor(...initialProducts: [string, Product][]) {
        initialProducts.forEach(p => this[p[0]] = p[1]);
    }
 
    [propertyName: string]: Product;
}

let group = new ProductGroup(["shoes", new SportsProduct("Shoes", 
    "Running", 90.50)]);
group.hat = new SportsProduct("Hat", "Skiing", 20);

let total = group.hat.price + (group.boots?.price ?? 0);
console.log(`Total: ${total}`);

In `src/index.ts`, `(group.boots?.price ?? 0)` lets the total use zero when the indexed product is missing. Optional chaining protects the property access; nullish coalescing supplies the numeric fallback. section 11.5.1

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains operand behavior through worked JavaScript expressions and applies it to property access without examining operator internals.
Examples
Uses a zero-rated tax calculation, object-price fallbacks, and a missing indexed product.
What it assumes
Builds on JavaScript expressions and object property access while introducing the difference between falsy and nullish values.
What you can do after
Diagnose/debug with it when logical OR replaces a legitimate zero or an optional property needs a fallback.
How it connects
Connects logical OR, falsy values, optional chaining, and TypeScript index-signature checks.

Also explained in

Compare how 3 books explain nullish coalescing operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.