🎁

12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
05 : 14 : 04 : 32
Join egghead, unlock knowledge.

Want more egghead? It's 58% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 40% Off
1×
Become a member
to unlock all features
Autoplay

    Optional Chaining with TypeScript 3.7

    Rich BuggyRich Buggy
    typescriptTypeScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    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.