DEV Community

Cover image for 2 Methods for Dealing with Nulls in TypeScript
Joe Eames for Thinkster

Posted on

2 Methods for Dealing with Nulls in TypeScript

TypeScript is such a cool language, and learning to use the more advanced features of it can be a real benefit to your code base.

I'd like to talk about one specific item: dealing with non-nullabe types.

Often times in our code we do something like the following:

image

This function should only run on actual users, but if user objects can possibly be null we guard our functionality by writing a null check around our code.

What we would like is the following:

image

And we can have this with TypeScript. There's a couple of ways to go about it:

Method 1:

The first is to just make your entire code base require you to explicitly declare nulls. You can do that with the - strictNullChecks flag which ensures that all variables are non-nullable unless you explicitly declare them as such. For example:

image

The above code would throw an error with the strict null check. You're creating a user, and initializing it to null, but not declaring it as a nullable type. In order to do that, and make it possibly be nullable, use the union operator like so:

image

This won't throw a TypeScript error. this user object can now either be a User or a null.

This way, you never have to write the null check unless the function can operate on both real objects AND nulls.

Method 2:

Now maybe making the entire code base explicit is too much. In that case, you can instead mark specific identifiers as non-nullable using the NonNullable generic type. For example, the above function can be re-written like this:

image

TypeScript will then give you errors if you ever try to call this function with an object that could possibly be a null. VERY easy and simple.

Now of the two methods, I personally prefer the first one. Yes, it seems like it's more restrictive, but in my experience, 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.

Utilize these tips, brought to you by the Angular Denver conference to make your TypeScript code a bit more manageable.

Happy coding!

Signup for my newsletter here.

Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @gothinkster

Top comments (0)