← Back to Gists

Optional chaining

📝 TypeScript
vdavis
vdavis · 5d ago
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 3d ago
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.