What are the Best ways to Handle Null in TypeScript?

1+

Best ways to Handling Null in TypeScript

Handle null is a biggest nightmare for any developers. As I, developer faced this problem multiple time. That’s why I come with the solution. In this article we are discussing two best way to handle null in Typescript.

Typescript is the advanced version of Javascript. Now a days It becomes the necessity of every web developers. And the Null is the common error and we should know the proper way to handle this.

What are the Best ways to Handle Null in TypeScript?

Before moving forward, A funny quotes, I remember on Null pointer exception.

You are the null pointer exception for me…🤣🤣🤣

Well know let’s focus on the two way to handle null in Typescript.

Let’s take an example before moving to the methods:

We have a function named updatePassword with User type of parameter. This function should be run on actual user objects which is non-nullable types.


Now we have to guard our functionality by writing null check if user objects would be null in any case.

First Method: ✔️

We can handle null by strictNullchecks  flag which ensures that the all variable would be non-nullable. For example:

What happens with above code? 😶‍🌫

It will throw an error with strict null check. Because when you are creating a user, and initialize with null. But not declaring as a nullable type.

In order to do that you have to make them nullable and for that we can use union operator.

looks creepy!! isn’t it? 🌚

But this won’t throw a TypeScript error. this user object can now either be a User or a null. Now let’s move to the second method to handle null in typescript.

Read this too: VDOM Stack (Vue Deno Oak MongoDB) CRUD example

Second method: ✔️

You can say that in the first method we handle the exception explicitly which make our code to much verbose. In this method, we are going to mark our objects as a NonNullable. Now our function looks like:


When you try to run this method with null objects then Typescript will throw an error. How easy it is. isn’t it?

Conclusion: 😏

After seeing the both methods to handle null in typescript, I prefer to choose the first method. Because of the most variables will never need to contain a null value for most of the execution. So, it’s easier to just explicitly mark the few places where you can either have an actual value or a null.

Which method you love to use with your code. Comment us with your thought below. 🗨️

 

 

1+
Summary
What are the Best ways to Handle Null in TypeScript?
Article Name
What are the Best ways to Handle Null in TypeScript?
Description
Handle null is a biggest nightmare for any developers. As I, developer faced this problem multiple time. That's why I come with the solution. In this article we are discussing two best way to handle null in Typescript.
Author
Publisher Name
Das JS
Publisher Logo