Dream features in New Typescript 3.7 are coming: Optional Chaining and Nullish Coalescing

Azat Nobatov
2 min readOct 2, 2019

--

TypeScript 3.7 is in Beta version, however, if you want to check it out you can install via npm:

npm install typescript@beta

1. Optional Chaining

Let’s assume we have an object car:

Also, we want to check if the sale property contains a value then do something. Most likely we would have written such if condition:

if (car && car.price && car.price.sale) {  
//...
}

Now, with optional chaining we can do as follows:

if (car?.price?.sale) {
//...
}

So, what is the ?. operator?

In optional chaining the ?. operator allows us to stop some expressions whenever we find null or undefined.

Or with ternary operators:

const salePrice = (car && car.price && car.price.sale) 
? car.price.sale
: undefined;

However, with ?. optional chaining operator it is as easy as follows:

const salePrice = car?.price?.sale;

Basically, it immediately stops the expression when a property of the object equals to null or undefined.

2. Nullish Coalescing

Let’s suppose we want to check for sale price if it is available then use it otherwise get the price from by calling some function. We would write the code like:

const price = (salePrice !== null  || salePrice !== undefined)
? salePrice
: getSalePrice();

However, the nullish coalescing operator allows us to make it much simpler:

const price = salePrice ?? getSalePrice();

Basically, it says use salePrice if it is available otherwise call getSalePrice() function. It is quite simple, isn’t it? :)

This is my first blog, despite my 7+ years of experience in web development, I never had a chance to write a blog -_-

I hope you found it useful… If you like it, give a clap or claps ;)

📝 Read this story later in Journal.

👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.

--

--