TypeScript Reference ยท Type Operators
TypeScript optional chaining (?.)
Reference for TypeScript optional chaining: ?. for properties, elements and calls, short-circuiting, the resulting undefined type and common mistakes.
Optional chaining, written ?., reads a property, an element or calls a function only when the value in front of it is not null or undefined. If the value is nullish, the whole chain stops and evaluates to undefined instead of throwing a TypeError.
TypeScript understands the operator in the type system: the type of a?.b is the type of b with undefined added whenever a can be null or undefined. Under strictNullChecks this forces you to deal with the missing case.
type User = { profile?: { city: string } }; declare const user: User; const city = user.profile?.city; // string | undefined
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
obj?.prop
obj?.[expression]
func?.(args)
| Form | Description |
|---|---|
a?.b |
Property access. Gives undefined when a is null or undefined. |
a?.[k] |
Element access with a computed key. The key expression is not evaluated if a is nullish. |
a?.(x) |
Call. The function is invoked only when a is not nullish; arguments are not evaluated otherwise. |
Result type: the type of the plain access, plus undefined when the left side may be nullish. Nullish means exactly null or undefined; other falsy values such as 0, "" or false continue the chain.
Edge cases: the operator does not catch errors. If a is a non-nullish value without the property, normal rules apply, and calling a non-function with ?.() still throws.
Usage notes
- Short-circuit covers the whole chain. In
a?.b.c.d, ifais nullish,.b.c.dis skipped. You only need another?.whenborccan itself be nullish. - Parentheses end the chain.
(a?.b).cevaluatesa?.bfirst and then reads.cof a possiblyundefinedresult, which is a type error under strict mode. - Combine with a default.
a?.b ?? "n/a"uses nullish coalescing to supply a fallback. - Not for assignment.
a?.b = 1is a syntax error. Check the value first with anif. - Do not overuse it. Putting
?.on values that are never nullish hides real bugs and, with some lint settings, is reported as an unnecessary condition. delete a?.bis allowed and returnstruewhenais nullish.- Narrowing:
if (a?.b !== undefined)narrowsato non-nullish inside the block. - Availability: supported since TypeScript 3.7. The compiler can downlevel it for older targets.