Search⌘ K

Optional Chaining and Optional Element Access

Explore how optional chaining in TypeScript eliminates the need for repetitive null and undefined checks when accessing nested object properties. Understand practical examples of using the ?. operator to safely access elements and properties, improving code readability and reducing errors related to null references.

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.

TypeScript 3.3.4
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 ...