0
0
Typescriptprogramming~5 mins

Optional chaining with types in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is optional chaining in TypeScript?
Optional chaining is a syntax that allows you to safely access nested object properties without causing an error if a property is null or undefined. It uses the ?. operator.
Click to reveal answer
beginner
How does optional chaining help with types in TypeScript?
It helps by preventing runtime errors when accessing properties that might not exist, and TypeScript understands this to allow safer code with better type checking.
Click to reveal answer
beginner
What will this expression return if user is null? <br>user?.name
It will return undefined instead of throwing an error because optional chaining stops the access if user is null or undefined.
Click to reveal answer
intermediate
Can optional chaining be used with function calls? Give an example.
Yes. For example, obj?.method() calls method only if obj is not null or undefined. Otherwise, it returns undefined.
Click to reveal answer
intermediate
What happens if you use optional chaining on an array element like arr?.[0]?
It safely accesses the first element of arr only if arr is not null or undefined. If arr is null or undefined, it returns undefined without error.
Click to reveal answer
What does the optional chaining operator ?. do in TypeScript?
AThrows an error if the value is null or undefined
BStops property access if the value is null or undefined and returns undefined
CAlways returns null
DConverts the value to a string
Which of these is a valid use of optional chaining?
Auser?.address?.street
Buser.address?.street
Cuser?.address.street
Duser.address.street?.
What will obj?.method() do if obj is undefined?
ACall method and throw error
BReturn null
CCall method with undefined context
DReturn undefined without calling method
Can optional chaining be used to safely access array elements?
AYes, like <code>arr?.[0]</code>
BNo, it only works with objects
CYes, but only with numbers
DNo, it causes syntax error
If user is null, what does user?.name ?? 'Guest' return?
AThrows error
Bnull
C'Guest'
Dundefined
Explain how optional chaining improves safety when accessing nested properties in TypeScript.
Think about what happens if a property is missing or null.
You got /4 concepts.
    Describe the difference between using optional chaining and normal property access in TypeScript.
    Consider what happens when you try to access a property on null or undefined.
    You got /4 concepts.