Optional chaining
- TypeScript course
- Beginner
- Lesson 64/89
- 4 min
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); // undefinedEven 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, safePractice 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.
Starter code
// User arayüzü tanımla: name ve isteğe bağlı address
// address bir nesnedir, içinde city: string bulunur
// cityOf(u: User): string döndürür
// address varsa şehri döndür
// yoksa "bilinmiyor" döndürSample 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" }));Expected output
Bursa bilinmiyor
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
Explanation: Optional chaining (?.) short-circuits; when the left side is null or undefined, it returns undefined instead of accessing the property or throwing.
2 Complete the optional chaining operator
const bio = user.profile____bio;
const bio = user.profile?.bio;
Explanation: Optional chaining ?. short-circuits when profile is null or undefined, returning undefined without accessing bio. The . always accesses and throws when undefined.
3 Optional chaining parts
| Term | Meaning |
|---|---|
?. |
Safe access operator |
undefined |
Short-circuit result |
u.profile?.bio |
Safe chained access |
u.profile.bio |
Throws when undefined |