TypeScript
Optional Chaining
Safely access deep properties.
By EZ4Code Team
optional-chainingoptional
Code
interface User {
profile?: {
address?: {
city?: string;
};
};
getName?(): string;
}
const user: User = {};
// Optional chaining avoids errors
const city = user?.profile?.address?.city;
const name = user?.getName?.();
// Array access
const first = arr?.[0];
// Function call
const result = obj?.method?.();
// Combined with nullish coalescing
const display = user?.profile?.address?.city ?? "unknown";Explanation
Optional chaining ?. short-circuits to undefined when any part of the chain is null/undefined.