Open In App

TypeScript strictNullChecks off Type

TypeScript strictNullChecks off Type will allow to access the null and undefined values. With strictNullChecks off, values that might be null or undefined can still be accessed normally, and the values null and undefined can be assigned to a property of any type. TypeScript is more permissive with null and undefined, and they are treated as assignable to all types. This means you can assign null and undefined to any variable.

Where we can set strictNullChecks?

In tsconfig.json: tsconfig.json file is a file of JSON format which allows us to point the root level files and different compiler options to set that are required to compile a TypeScript-based 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": false, 
        "outFile": "../JS/TypeScript/HelloWorld.js", 
        "sourceMap": true
}, 
    "files": [ 
        "program.ts", 
        "sys.ts"
    ], 
    "include": [ 
        "src/**/*"
    ], 
    "exclude": [ 
        "node_modules", 
        "src/**/*.spec.ts"
    ] 
}

Example 1: In this example even though we assigned null and undefined to variables but typescript did not thrown any error since strictNullChecks is off (set to false).




let myVar: string = null; // No error
let anotherVar: number = undefined; // No error
console.log(myVar)
console.log(anotherVar)

Output:



Example 2: In this example, we will see that compiler will throw error for assigning null and undefined values when strictNullChecks is on(set to true).




let myVar: string = null;
let anotherVar: number = undefined;
console.log(myVar)
console.log(anotherVar)

Output:

Conclusion: In this article, we have seen strictNullChecks off Type and we can set it by Ts config file. It helps in checking type of variable. Also it helps in preventing the run time errors. we can toggle it (true to false) accroding to our need.


Article Tags :