Optional Chaining and Optional Element Access
This lesson explains a feature of TypeScript 3.7 that will reduce the boilerplate of code when checking undefined/null type.
The object property chaining situation
Any language that has the possibility of a null
value (and undefined
for TypeScript) gets into a situation where a nested property is needed but within the chain of nested objects, that many variables can be null
. Hence, they need to be checked.
The following code does not compile.
The reason is that you are accessing a nested property but at level1
, level2
, or level3
, there is a chance that the variable is not defined (see lines 2 to 4 which indicates optional). This would cause a null reference exception.
Get hands-on with 1200+ tech skills courses.