StrictNullChecks in TypeScript

StrictNullChecks in TypeScript introduces stricter type checks for null & undefined. This option was introduced in TypeScript 2.0. We enable it by setting  strictNullChecks: true in the tsconfig.json, which ensures that the compiler will raise an error if we assign Null and Undefined to other types.

Strict null checks

Null and Undefined are special values that represent no value. We can assign them to all other types like numbers, strings, etc. Such assignment has been the source of a lot of errors like Uncaught TypeError: Cannot read property ‘propertyName’ of undefined/null etc, in JavaScript. This error is thrown when we try to access a property on an undefined or null object.

TypeScript prior to version 2.0 never warned us when we tried to access a property of the null or undefined object. In the following example, passing null in sayHello function does not throw any compile-time error. But when you run the code you will get an (Cannot read properties of null) error.

Enabling StrictNullChecks

To enable StrictNullChecks open tsconfg.sys and add "strictNullChecks": true under the compilerOptions.

With this set to true, you’ll get a type error if you try to use null or undefined wherever Typescript expects a concrete type.

For Example, code from the previous section results in a compiler error Argument of type 'null' is not assignable to parameter of type. This enables us to fix the error and does not have to wait for the code to run and crash.

Null & Undefined under StrictNullChecks

  1. The undefined is assignable only to any, void & undefined
  2. Nothing is assignable to undefined except neverany & undefined
  3. null is assignable only to any & null
  4. Nothing is assignable to null except another null

The following section lists some of the common errors that arise when you enable strict null checks and solutions for them.

Variable foo is used before being assigned.

Trying to use a variable before initializing it will result in a compiler error.

The solution is to assign a value to it at the time of initialization.

Assigning null or undefined

With StrictNullChecks set to true, we cannot assign null or undefined other data types. But this is not practical in real life.

In the following example, we cannot assign null or undefined to numVar.

To allow a variable to accept null or undefined, we need to explicitly set it. We can do that by creating a union type.

You can use a similar strategy when you want to pass null to a function as an argument.

To pass undefined, you can also make use of the optional parameter ?

You can also create a union type of person and undefined. But here you must pass a value for the person. not Passing a value will result in an error.

This will allow all three but you must pass a value

is will allow all three & person is given the value undefined if no value is passed

Object is Possibly undefined / Null

Passing null or undefined to a function and using it will result in the Object is possibly null or Object is possibly undefined error.

For Example, the following code results in the compiler error at the console.log statement. Since nulls are allowed, the TypeScript compiler thinks that the p could be possibly null.

There are a few ways in which you can solve the above problem.

Use if to check for null

If condition to check for null or undefined. Since we checked for null in the if condition, it is guaranteed that the p will never be null in the else statement. The TypeScript compiler is smart enough to understand and this does not throw any errors. This behavior is known as Type Guards.

Non-null assertion operator!

! is a Non-null assertion operator introduced in TypeScript 2.0. We use this operator to inform the Type checker that its operand is not null or undefined.

The code below p! tells the compiler that p is not null or undefined. Hence the compiler does not throw any errors.

But if you actually pass a null object, then you will get a run time error. Hence use this operator only if you are very sure that it will never be null or undefined.

Use Optional Chaining using?

Using optional chaining causes the run time to stop the execution if it encounters a null or undefined and return undefined.

For example in the code below, if the foo is defined then the bar.baz() is computed. But if foo is null or undefined then run time will stop the further execution and it returns undefined.

Hence In the following code when we pass null, no errors are thrown. But when p is null p?.name returns with the value undefined.

Nullish Coalescing

The nullish coalescing operator (??) is a logical operator that takes two arguments. It returns the right-hand side operand when its left-hand side operand is null or undefined. otherwise, it returns its left-hand side operand.

The Nullish Coalescing can be used to provide a default value if the expression is null.

In the following code if foo is null (or undefined) then the code will return bar() else it will return foo

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top