Careeroza
Optional Chaining
The ?. Operator
a?.b returns undefined instead of crashing when a is null or undefined. It works for properties (a?.b), indexes (a?.[0]) and calls (fn?.()). TypeScript adds undefined to the result type.
Example
type User = {
name: string;
address?: { city: string; geo?: { lat: number; lng: number } };
orders?: { id: string }[];
onLogout?: () => void;
};
const u1: User = { name: "Ravi", address: { city: "Pune", geo: { lat: 18.52, lng: 73.85 } }, orders: [{ id: "OD-1" }] };
const u2: User = { name: "Guest" };
for (const u of [u1, u2]) {
console.log(u.name, u.address?.city, u.address?.geo?.lat, u.orders?.[0]?.id);
u.onLogout?.(); // called only if it exists
}Output
Ravi Pune 18.52 OD-1 Guest undefined undefined undefined
Without ?. the Compiler Complains
Example
address is optional, so direct access is TS18048 ("possibly undefined").
type User = { name: string; address?: { city: string } };
const u: User = { name: "Guest" };
console.log(u.address.city);Compiler output (tsc)
Line 3: error TS18048: 'u.address' is possibly 'undefined'.