typescript / beginner
Snippet
Optional Chaining
Optional chaining (?.) allows you to read properties deep within a chain of objects without having to manually check if every reference in the chain exists.
snippet.ts
1
2
3
const data: any = { user: { id: 1 } };const userName: any = data?.user?.name;console.log(userName);
Breakdown
1
data?.user
Checks if 'data' is null or undefined before attempting to access the 'user' property.
2
?.name
If 'user' exists, it tries to get 'name'; otherwise, it stops and returns undefined without crashing.