Open In App

How to enforce strict null checks in TypeScript ?

In Typescript to enforce strict null checks in tsconfig.json file, we need to enable “strictNullChecks” to true. When “strictNullChecks” is false, the language generally ignores variables of type null and undefined. If null and undefined is used in places where a definite value is expected, it raises an error. When “strictNullChecks” is true when null and undefined is used a type error gets raised.

Example 1: Assigning null and undefined to string type variable



A null value is passed to a string-type variable.




let var1: string = null;

Output:



When strict null checks are enabled.

If strict null checks are not enabled:

If undefined is given to a variable and strictnullchecks is true:




let var1: string = undefined;

Output:

Example 2: Referencing variables before assigning values

When strictnullchecks are enabled variables that are not assigned any value cannot be referenced. The only exception is when the variable is of type “undefined”, those variables can be referenced before being assigned by any value. 




let var1: string | number;
let var2: string | null;
let var3: string | undefined;
  
// Throws error
var1;
  
// Throws error
var2;
  
// Doesn't Throws error
var3;
var1 = 1;
var2 = "abc";
  
// No error
var1;
  
// No error
var2;

Output: This is how it looks like in code editor.

Example 3: Covering strictnullchecks

The below code is a small example of strictnullchecks. An interface is created and ?: is used while declaring variable age, it says the variable can be null or identified. As strict null checks are enabled when we try to display student.age it gives us warning. When it’s further confirmed that student.age is not null no warning or error is given. 




interface Student {
  name: string;
  age?: number;
}
  
function displayStudentInfo(student: Student) {
  
  // Error TS2532: Object is possibly 'undefined'.
  console.log(student.name + ` , ${student.age.toString()}`);
  
  // Confirming that student.age is not null
  console.log(student.name + ` , ${student.age!.toString()}`);
  
  // Condition is checked that student's age isn't null
  if (student.age != null) {
    console.log(student.name + ` , ${student.age.toString()}`);
  }
}
  
let obj: Student = { name: "sean", age: 20 };
console.log(displayStudentInfo(obj));

Output: 

sean , 20
sean , 20
sean , 20

Article Tags :