Chooce video playback speed
speed:1

Optional Chaining with TypeScript 3.7

InstructorRich Buggy

Share this video with your friends

Send Tweet

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.

This lesson is a Community Resource

A Community Resource means that it’s free to access for all. The instructor of this lesson requested it to be open to the public.

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.