Open In App

TypeScript strictNullChecks off Type

Last Updated : 06 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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"
    ] 
}
  • 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 even though we assigned null and undefined to variables but typescript did not thrown any error since strictNullChecks is off (set to false).

Javascript




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


Output:z77

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).

Javascript




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


Output:z80

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads