← Back to Gists

Optional chaining

📝 TypeScript
vdavis
vdavis · Level 2 ·

Optional chaining lets you safely access deeply nested properties without throwing an error if an intermediate value is null or undefined.

TypeScript
const user = { name: "Alice", address: null,
}; const city = user.address?.city; // undefined, no error
const street = user.address?.street ?? "unknown";
console.log(city, street); // undefined "unknown"

Comments

1
jenna jenna

Yes, exactly - user?.profile?.address?.city is a lifesaver for cleaning up API response handling. One caveat: it can mask bugs if you overuse it instead of validating data at the boundary.