TypeScript
Optional chaining
Learn safe access with the ? operator.
What is optional chaining?
Optional chaining (?.) provides safe access to a property. If the left side is null or undefined, it short-circuits and returns undefined instead of throwing.
interface User { name: string; profile?: { bio: string }; }
const u: User = { name: "Ada" };
console.log(u.profile?.bio); // undefined
Even if profile is undefined, the app does not crash.
Safe and unsafe access
Normal access (.) throws when the left side is undefined, crashing the app. Optional chaining (?.) instead short-circuits and returns undefined. The short-circuit can happen at any point along the chain.
interface User { name: string; profile?: { bio: string }; }
const u: User = { name: "Ada" };
// u.profile.bio throws (profile is undefined)
console.log(u.profile?.bio); // undefined, safe
Exercise Get the city with optional chaining
Define a User interface: name: string and an optional address. The address is an object containing city: string. Write a function cityOf(u: User): string: if address exists, return the city; otherwise return "bilinmiyor". Call it with two examples and print the results.
Show example solution
interface User {
name: string;
address?: { city: string };
}
function cityOf(u: User): string {
const city = u.address?.city;
if (city === undefined) {
return "bilinmiyor";
}
return city;
}
console.log(cityOf({ name: "Ada", address: { city: "Bursa" } }));
console.log(cityOf({ name: "Bob" }));
Test yourself
-
What does u.profile?.bio return when u.profile is undefined?
interface User { name: string; profile?: { bio: string }; }
const u: User = { name: "Ada" };
console.log(u.profile?.bio);
- throws an error
- returns an empty string
- returns null
- returns undefined
Show answer
returns undefined — Optional chaining (?.) short-circuits; when the left side is null or undefined, it returns undefined instead of accessing the property or throwing.
-
Complete the optional chaining operator
const bio = user.profile____bio;
Show answer
const bio = user.profile?.bio;
-
Optional chaining parts
- ?.
- Safe access operator
- undefined
- Short-circuit result
- u.profile?.bio
- Safe chained access
- u.profile.bio
- Throws when undefined
Next lesson: Nullish coalescing