TypeScript 3.7 adds support for optional chaining. This lesson shows you how to use it in your code to handle properties that can be null or undefined.
Instructor: I'm going to start by defining two interfaces. Interface A will have an optional property B of type B. Interface B will have a property C of type String. I'll then assign an object to the variable A with B and C defined. Finally, I'll log the value of C to the console. When I compile and execute the code, you see the output "Hello, World!"
The problem with this code is that an empty object is also a valid value for A. If I compile my code and run it, I get an error because B is undefined, so it cannot access the property C. Starting with version 3.7, TypeScript supports optional chaining. This allows me to place a question mark after the B, which tells TypeScript to check if B is null or undefined before it tries to access property C.
If B is null or undefined, it will immediately terminate the chain and return the value undefined. When I compile and execute my code now, I see the value undefined.
You must be a Pro Member to view code
Access all courses and lessons, track your progress, gain confidence and expertise.