Optional chaining and the ?? operator in TypeScript 3.7

Sven Mutzl
Nov 6 · 2 min read

The latest typescript version provides a new operator that can same a lot of time and can make your code way better to read. It the new ?? operator. Even if you don’t plan to use it you will sooner or later see it in some code and wonder what it does.

Please make sure you updated your typescript by doing:

// maybe you need to add sudo
npm install -g typescript

Now that we have the latest version installed we can have a look at an example.

let x = foo ?? bar//before 3.7:
let x = (foo!==null && foo!==undefined) ? foo : bar

What it does is to set the variable x to the value of foo if foo is neither null nor undefined. Otherwise it will set it to bar.

Lets say you receive parameter via an api as optional query parameters. You might want to allow a user to set a limit for the number of records. In this case you could now just do:

const limit = res.query.limit ?? 5

Another really cool feature is optional chaining. Lets say that your res object from the previous example does not always has a query parameter. In this case you might get an error that you try to access the parameter limit on something that is undefined.

With optional chaining you can simply do:

const limit = res.query?.limit//instead of
const limit = (res.query===null ||res.query===undefined) ? res.query.limit : undefined

In combination you can now safely ask try to set the variable with also setting a default by just:

const limit = res.query?.limit ?? 5

I think it looks very nice and I am looking forward to use it soon in real projects.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade