In TypeScript, ’strict null checks’ is a compiler option that enforces stricter type checking rules. When this option is enabled, the types ‘null‘ and ‘undefined‘ are treated as distinct types from every other type, making it impossible to inadvertently use them in an unsafe manner. The strict null checks option can be activated by adding the ‘"strictNullChecks": true‘ flag to the ‘tsconfig.json‘ file or using the ‘–strictNullChecks‘ command line flag with the TypeScript compiler.
The objective of strict null checks is to catch potential bugs and improve the safety of your TypeScript code. Let’s see how it works and why it is useful with some examples:
1. Without strict null checks:
function greet(name: string) {
return `Hello, ${name}!`;
}
const user: string = null;
console.log(greet(user)); // TypeError: Cannot read property 'toUpperCase' of null
Here, since the ‘user‘ is ‘null‘, at runtime you would get an error, but TypeScript doesn’t show an error at the compile-time because it considers the ‘null‘ to be a valid value for type ‘string‘. This may lead to undetected bugs in your code.
2. With strict null checks:
function greet(name: string) {
return `Hello, ${name}!`;
}
const user: string = null; // Error: Type 'null' is not assignable to type 'string'.
console.log(greet(user));
When using strict null checks, TypeScript will report an error when trying to assign ‘null‘ to a variable of type ‘string‘. This helps you detect and fix potential null-related issues early, before the code runs.
To further illustrate the benefit of strict null checks, let’s take more complex example. We define a type ‘Person‘ and a function ‘getPersonAge‘:
type Person = {
name: string;
age: number;
};
function getPersonAge(person: Person): number {
return person.age;
}
const person: Person = null;
console.log(getPersonAge(person)); // RuntimeError: Cannot read property 'age' of null
Without strict null checks, we encounter the same problem as before - this code would give an error at runtime, but TypeScript wouldn’t catch it at the compile-time.
But when we enable strict null checks, TypeScript shows an error at the line of assigning ‘null‘ to ‘person‘:
const person: Person = null; // Error: Type 'null' is not assignable to type 'Person'
Now, we are forced to provide a valid ‘Person‘ object or handle the ‘null‘ case explicitly. This guarantees that we don’t run into runtime errors caused by undefined or null values.
In general, strict null checks help you create more robust and safer TypeScript code, making it easier to identify and handle potential issues related to ‘null‘ and ‘undefined‘ values. By enforcing strict typing, it encourages you to write clearer and more predictable code, reducing the likelihood of errors and simplifying debugging.