...
/Optional Chaining and Optional Element Access
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.
Press + to interact
interface MyType {level1?: {level2?: {level3?: {name: string;}}}}let ex1: MyType = {level1: {level2: {level3: {name: "Good"}}}}console.log(ex1.level1.level2.level3.name)
Previous art solutions to chaining
Before TypeScript 3.7, the ...