Skip to content
tezvyn:

TypeScript's Optional Chaining (`?.`)

Source: typescriptlang.orgMediumHow cards are made

TypeScript's Optional Chaining (`?.`)

Optional chaining (?.) lets you safely access nested properties without crashing on null or undefined. Use it to replace verbose && checks when traversing deep objects. The footgun is that it only checks the value to its left, not the entire chain.

Why it exists

JavaScript developers frequently need to access properties deep inside an object. Before optional chaining, this required a series of checks like if (foo && foo.bar && foo.bar.baz) to avoid a TypeError: Cannot read properties of null/undefined. This code is verbose, repetitive, and error-prone.

The mental model

Think of optional chaining (?.) as a "maybe" operator for property access. When you write foo?.bar, you're telling TypeScript: "If foo exists, give me foo.bar. If foo is null or undefined, just stop and give me undefined without throwing an error." It's a built-in safety check for traversing potentially incomplete data structures.

How it works

The ?. operator short-circuits an expression. If the operand on the left of ?. is null or undefined, the rest of the expression is not executed, and the entire chain evaluates to undefined. This works for three scenarios: first, optional property access (obj?.prop); second, optional element access (arr?.[0]); and third, optional function calls (callback?.()). For example, foo?.bar.baz() is equivalent to (foo === null || foo === undefined) ? undefined : foo.bar.baz().

When to use it

Use optional chaining when dealing with data where properties might not exist, such as API responses, configuration objects, or any deeply nested structure. It's perfect for cleaning up code that has many chained && checks. It's also excellent for invoking optional callback functions that may or may not be provided as arguments.

When not to use it

Avoid optional chaining when a missing property represents a true error state that should halt execution. If user.id is required for your logic to function correctly, letting user?.id fail silently to undefined can hide bugs. Also, note that it does not short-circuit on other "falsy" values like 0 or an empty string, which is different from how && chains behave.

One canonical example

A common use case is safely calling an optional logging function passed into a method. Consider async function makeRequest(url, log). Instead of writing if (log != null) { log('message'); }, you can simply use an optional call: log?.('Request started'). If log is undefined, nothing happens; if it's a function, it gets called.

Interview question

Consider the expression `config?.settings?.theme`. If `config` is `null`, what is the final result of this expression?

  • a.The entire expression evaluates to `undefined`.Correct
  • b.It attempts to access `settings` on an empty object `{}`.
  • c.A TypeError is thrown when trying to access `settings` on `null`.
  • d.Only `config?.settings` is evaluated, then `theme` is accessed.
Why?

Optional chaining (`?.`) short-circuits immediately if the value to its left is `null` or `undefined`. In this case, since `config` is `null`, `config?.settings` evaluates to `undefined`, and the rest of the chain (`.theme`) is not executed. Option C is incorrect because `?.` specifically prevents `TypeError` for `null` or `undefined` values.

Just read this? Test yourself on what you have been reading.

Read the original → typescriptlang.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on typescript — each one lists the topics its interview covers.

See open roles