TypeScript strictNullChecks on Type

TypeScript strictNullChecks on Type is used to check the type of the given value. When strictNullChecks is turned on (which is generally recommended for safer code), TypeScript enforces stricter rules regarding null and undefined. You cannot assign null or undefined to a variable unless its type explicitly allows it, or you use type assertions.

Where we can set strictNullChecks?

In tsconfig.json: tsconfig.json file is a file of JSON format that allows us to point to the root level files and different compiler options set that are required to compile a TypeScript project. The existence of this file in a project specifies that the given directory is the TypeScript project folder root.

{ 
"compileOnSave": true,
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"allowUnreachableCode": false,
"strictNullChecks": true,
"outFile": "../JS/TypeScript/HelloWorld.js",
"sourceMap": true
},
"files": [
"program.ts",
"sys.ts"
],
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"src/**/*.spec.ts"
]
}
  • When strictNullChecks is false, null and undefined are effectively ignored by the language. This can lead to unexpected errors at runtime.
  • When strictNullChecks is true, null and undefined have their own distinct types and you’ll get a type error if you try to use them where a concrete value is expected.

Example 1: In this example, we will create a function and and pass a null value here. We need to test for this value for null before using methods or properties on that value

Javascript




function gfg(x: string | null) {
    if (x === null) {
        console.log("GFG")
    } else {
        console.log("Hello, " + x.toUpperCase());
    }
}
gfg("w3wiki")


Output:

Example 2: In this example, we are checking for undefined value before using it since strictNullChecks is true

Javascript




// Compiler Option: "strictNullChecks": true
  
function greet(name: string) {
    if (name === undefined) {
        return ("undefined")
    }
    else {
        return `Hello, ${name}!`;
    }
}
let personName: string = "w3wiki";
console.log(greet(personName));


Output:

Conclusion: In this article we have seen strictNullChecks on Type and from where we can enable it. It increases code readability and decreases run time issues and helps in fixing type checking bugs.