0Pricing
TypeScript Academy · Lesson

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 crash

Optional 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

  1. Optional Chaining with ?.
  2. Nullish Coalescing with ??
  3. Combining ?. and ??
  4. Optional Calls and Element Access
← Back to TypeScript Academy