Optional Calls and Element Access
Use ?.() and ?.[] for safe method calls and indexing.
Beyond Property Access
Optional chaining isn't limited to obj?.prop. It has two more forms: optional calls with ?.() and optional element access with ?.[index]. Both short-circuit on nullish, just like property access.
type Obj = { greet?: () => string };
const o: Obj = {};
console.log(o.greet?.()); // undefined, no crashOptional Method Calls
Use obj.method?.() to call a method only if it exists. If method is null or undefined, the call is skipped and the expression yields undefined.
type Logger = { log?: (m: string) => void };
const silent: Logger = {};
silent.log?.('hello'); // skipped, no error
console.log('continued safely');All lessons in this course
- Optional Chaining with ?.
- Nullish Coalescing with ??
- Combining ?. and ??
- Optional Calls and Element Access