Null (Undefined) Safety in TypeScript

Arman Kolahan
2 min readNov 28, 2020

One of the most common issues in developing JavaScript is checking the var is defined or not. By TypeScript, you can cut off the excess if statement that you have to use.

The problem

Let's take a look at a simple example:

First, we defined a variable, namely user, as an object. And we logged the first name of the user. But what happens on the second log? It throws an error in the log! Because we haven’t defined user2.

How can we fix the problem? By adding an if statement!

This solution works, but it is annoying when you need to check to add an extra if statement.

The solution — Optional chaining (?.)

TypeScript helps to get rid of this type of if statements using optional chaining, which is just a question mark (?) we can use in a chain.

The above code is equivalent to the following code:

So, just by using an .? operator, you can code safer and shorter. It will be more useful when the chain is longer. Let's take a look at an example of a long-chain:

Use optional chaining operator (?.) in chains, makes your code safer and shorter.

Nullish Coalescing (??)

Nullish Coalescing is a useful operator that can be used to set a default value in case a variable is null or undefined.

Use nullish coalescing operator (??) for setting a default value

--

--

Arman Kolahan

Experienced frontend engineer & architect with over a decade of expertise in React. Proven leader and team builder. Passionate writer.