Skip to the solution
EasyFrontend9 min read

What are optional properties and optional chaining in TypeScript?

1.2k views

The problem

Question presented to candidate: "An API returns users where `email` and `address` are sometimes missing. How do you type those fields, and how do you read `user.address.city` without crashing? Walk me through optional properties and optional chaining."

What a strong answer should cover:

  • `key?: T` means the key may be absent; reading it gives `T | undefined` and must be narrowed under `strict`
  • `key?: T` is not the same as `key: T | undefined` (the second still requires the key); `in` tells "missing" from "present but undefined"; `exactOptionalPropertyTypes` makes the distinction strict
  • Optional chaining has three forms: `a?.b`, `a?.[k]` and `f?.()`, and the result type always adds `undefined`
  • Short-circuiting: once the left side is `null` or `undefined`, the rest of the chain, including function calls and index expressions, is not evaluated
  • `?.` guards only `null`/`undefined` (not `0` or `""`), only the link it is written on, and cannot be used on the left of `=`; pair it with `??` for defaults
  • Optional methods and `Partial<T>`

Code / implementation expected: Yes β€” an interface with optional fields and safe reads with `?.` and `??`.

  • optional
  • null-safety

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 7 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptOptional properties: missing keys, narrowing, in and Partial
TypeScriptOptional chaining: three forms, short-circuiting and limits

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 1 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

How do you make values immutable in TypeScript?

Continue