liveBook · Manning

Optional chaining

As explained in Pro Angular 16

The optional chaining operator conditionally accesses a property or invokes a method, yielding undefined when the preceding value is null or undefined.

Optional chaining uses ? to access a property or invoke a method only when the preceding value is neither null nor undefined; otherwise, it yields undefined. It avoids repeating explicit null and undefined guards. section 3.4.7

Formatting a nullable number

A nullable count can be formatted directly: `let count: number | undefined | null = 100; let result: string | undefined = count?.toFixed(2);`. With count set to 100, the result is `100.00`; with a nullish count, the expression produces undefined.

How Pro Angular 16 covers it

How deep it goes
Demonstrates guarded method invocation and contrasts it with explicit checks, without developing broader chaining patterns.
Examples
Uses a nullable numeric count and its toFixed method to compare explicit guarding with optional chaining.
What it assumes
Assumes TypeScript union types and nullable values, while demonstrating explicit null and undefined guarding before simplifying it.
What you can do after
Apply optional chaining in TypeScript to invoke methods without manually checking null and undefined first.
How it connects
Connects optional chaining with TypeScript union types, nullish coalescing, and null or undefined checks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.