Optional chaining helps you safely access properties or call functions on objects that might be null or undefined. It prevents errors when something is missing.
Optional chaining with types in Typescript
interface User {
name?: string;
address?: {
street?: string;
city?: string;
};
getAge?: () => number;
}
const user: User = {};
// Access property safely
const street = user.address?.street;
// Call function safely
const age = user.getAge?.();The ?. operator checks if the value before it is null or undefined. If yes, it stops and returns undefined instead of throwing an error.
Optional chaining works with properties, methods, and array elements.
undefined instead of error.const user = { name: "Alice" }; console.log(user.address?.street); // undefined
const user = { getAge: () => 30 }; console.log(user.getAge?.()); // 30
undefined safely.const user = {}; console.log(user.getAge?.()); // undefined
const users = [{ name: "Bob" }, null]; console.log(users[1]?.name); // undefined
This program shows how optional chaining safely accesses properties and methods on two users. The first user has all info, the second is missing some.
interface User {
name?: string;
address?: {
street?: string;
city?: string;
};
getAge?: () => number;
}
const user1: User = {
name: "John",
address: { street: "Main St", city: "Townsville" },
getAge: () => 25
};
const user2: User = {
name: "Jane"
};
function printUserInfo(user: User) {
console.log(`Name: ${user.name ?? "Unknown"}`);
console.log(`Street: ${user.address?.street ?? "No street info"}`);
console.log(`Age: ${user.getAge?.() ?? "Age not available"}`);
}
console.log("User 1 info:");
printUserInfo(user1);
console.log("\nUser 2 info:");
printUserInfo(user2);Time complexity is the same as normal property access, just a small check added.
Optional chaining returns undefined if the value before ?. is null or undefined.
Common mistake: forgetting that optional chaining returns undefined, so you might need to handle that case.
Use optional chaining when you expect some data might be missing, instead of writing many if checks.
Optional chaining ?. helps safely access properties or call methods on objects that might be missing.
It prevents runtime errors by returning undefined if something is null or undefined.
Use it to write cleaner and safer code when working with uncertain data.