With the addition of the optional chaining operator you’re able to reach deep object properties without checking for nullish (null or undefined) values in the chain.

As an example, let’s say you’re requesting user data from an API:

interface UserResponse {
  user: {
    email: string;
    name?: {
      firstName: string;
      lastName: string;
    };
  };
}

const response: UserResponse = await fetchUserData();

Previously, if we tried to access response.user.name.firstName without first checking response.user.name we get a runtime error if user has no name:

console.log(response.user.name.firstName);
// TypeError: Cannot read property 'firstName' of undefined

If using TypeScript with strictNullChecks enabled (see here) you can catch the error before runtime:

console.log(response.user.name.firstName);
            ~~~~~~~~~~~~~~~~~~
// error TS2532: Object is possibly 'undefined'`

Using the new optional chaining operator we can make this a bit nicer. Instead of throwing an error if the value is nullish, it’s returning undefined.

console.log(response.user.name?.firstName);
// output: undefined

This is currently an experimental feature which you can enable in Chrome +79 if you want to play with it. Visit chrome://flags/#enable-javascript-harmony and enable the flag.

For TypeScript users, it’s available in version 3.7.

For Babel users, you can set it up using the @babel/plugin-proposal-optional-chaining plugin:

{
  "presets": ["@babel/preset-env"],
  "plugins": ["@babel/plugin-proposal-optional-chaining"]
}