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.
When strict null checks are enabled.
If strict null checks are not enabled:
If undefined is given to a variable and strictnullchecks is true:
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.
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.
sean , 20 sean , 20 sean , 20