capypad
0 day streak
typescript / beginner
Snippet

Optional Chaining

Optional chaining allows you to safely access properties that may be null or undefined. If any part of the chain is missing, it returns undefined instead of throwing a runtime error.

snippet.ts
typescript
1
2
const user = { profile: { name: 'Alice' } };
const userName = user?.profile?.name;
Breakdown
1
user?.profile
Checks if 'user' is not null/undefined before accessing 'profile'.
2
?.name
Checks if 'profile' is not null/undefined before accessing 'name'.