Performing Null Checks with Optional Chaining in Typescript | Task

Ole Ersoy
Jan - 09  -  1 min

Scenario

We have a Customer property on our store instance that is always initialized and we want to skip the non null check in order to access the total function on each Customer instance.

const store:any = {};
if (store.customer) {
   const total = store.customer.total());
} 

Approach

With the Typescript Optional Chaining ( ? )Operator we can skip the if statement.

const total = store.customer?.total();

Demo