Optional Chaining in TypeScript

Optional chaining is a feature that allows you to access an object properties, read an array elements and call a method without a risk of causing a runtime error. Instead, if the object you are accessing is null or undefined, it will return undefined.
Optional chaining operator is ?.

Syntax

Object property

object?.property

Array element

array?.[index]

Method

method?.()

Example

interface Person {
  name: {
    firstName: string;
    lastName: string;
    fullName?: () => string;
  };
  age: number;
  contact?: {
    email: string;
    phone?: string;
  };
  hobbies?: string[];
}
const personA: Person = {
  name: {
    firstName: 'Jan',
    lastName: 'Kowalski',
    fullName() {
      return `${this.firstName} ${this.lastName}`;
    },
  },
  age: 32,
  contact: {
    email: 'jkowalski@larago.pl',
    phone: '123 456 789',
  },
  hobbies: ['programming'],
};

console.log(personA.name.fullName?.()); // Jan Kowalski
console.log(personA.contact?.phone); // 123 456 789
console.log(personA.hobbies?.[0]); // programming
const personB: Person = {
  name: {
    firstName: 'Adam',
    lastName: 'Nowak',
  },
  age: 64,
};

console.log(personB.name.fullName?.()); // undefined
console.log(personB.contact?.phone); // undefined
console.log(personB.hobbies?.[0]); // undefined