Optional Calls and Element Access
Use ?.() and ?.[] for safe method calls and indexing.
Optional Calls and Element Access is a free TypeScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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');Where to Put the ?.
The ?. goes right before the call parentheses. obj.method?.() checks method, not obj. To guard obj too, write obj?.method?.().
type Api = { send?: (x: number) => number };
const api: Api | null = null;
console.log(api?.send?.(5)); // undefined; guards both api and sendCalling Optional Callbacks
A very common use is invoking an optional callback parameter. Instead of an if check, write callback?.() to call it only when provided.
function run(onDone?: () => void): void {
console.log('working...');
onDone?.(); // call only if passed
}
run();
run(() => console.log('finished'));Optional Element Access
For arrays or index signatures that might be nullish, use arr?.[index]. If arr is nullish the access short-circuits; otherwise it reads the element normally.
const list: string[] | undefined = undefined;
console.log(list?.[0]); // undefined, no crashElement Access With Dynamic Keys
Optional element access also works with bracket notation for dynamic or computed keys on a possibly-nullish object.
type Dict = { [key: string]: number };
const data: Dict | null = { a: 1, b: 2 };
const key = 'a';
console.log(data?.[key]); // 1Combining Element Access and Calls
You can mix the forms freely. Reach into an optional array, then optionally call a method on the element — each ?. guards its own step.
type Handlers = Array<{ fire?: () => string }>;
const hs: Handlers | undefined = [{ fire: () => 'boom' }];
console.log(hs?.[0]?.fire?.());Optional Chaining With Function Results
You can chain off whatever a function returns. If the function yields nullish, subsequent calls or accesses short-circuit safely.
function getHandler(): (() => string) | undefined {
return undefined;
}
console.log(getHandler()?.()); // undefinedThe Result Type Includes undefined
As with property chains, optional calls and element access add undefined to the result type. Pair them with ?? to provide a default and drop the undefined.
type Obj = { compute?: () => number };
const o: Obj = {};
const value = o.compute?.() ?? 0;
console.log(value);Guarding Event Handlers
In UI and event code, optional calls elegantly invoke handlers that may not be set. No verbose existence check, no crash when the handler is absent.
type Props = { onClick?: (id: number) => void };
function click(p: Props, id: number): void {
p.onClick?.(id); // safe if onClick is missing
}
click({ onClick: (id) => console.log('clicked', id) }, 7);
click({}, 8);A Plugin Dispatcher Example
Putting it together: a dispatcher that optionally invokes a named plugin hook from a possibly-sparse registry, defaulting the outcome when nothing handles it.
type Hooks = { [name: string]: (() => string) | undefined };
const hooks: Hooks = { save: () => 'saved' };
function fire(name: string): string {
return hooks[name]?.() ?? 'no handler';
}
console.log(fire('save'), fire('delete'));Quick Check
Test your understanding of optional calls and element access.
Recap: Optional Calls and Access
You learned the other optional-chaining forms:
obj.method?.()calls a method only if it exists.arr?.[index]safely reads an element from a possibly-nullish container.- All forms short-circuit to
undefinedon a nullish operand. - Combine with
??to default the result.
Next course: readonly and immutability basics.
type Cfg = { init?: () => void };
const c: Cfg = {};
c.init?.();
console.log('ran safely');Frequently asked questions
Is the “Optional Calls and Element Access” lesson free?
Yes — the full text of “Optional Calls and Element Access” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Optional Calls and Element Access”?
Use ?.() and ?.[] for safe method calls and indexing. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Optional Calls and Element Access” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Optional Chaining with ?.
- Nullish Coalescing with ??
- Combining ?. and ??
- Optional Calls and Element Access