Strict null checks is a feature in TypeScript that enhances type safety by ensuring that null and undefined values are not assignable to types unless explicitly specified. This feature helps developers avoid common runtime errors that occur due to unexpected null or undefined values. By enabling strict null checks, TypeScript enforces a stricter type system, which can lead to more robust and maintainable code.
When strict null checks is enabled, the type system differentiates between types that can be null or undefined and those that cannot. This distinction allows developers to catch potential errors at compile time rather than at runtime.
In TypeScript, when strict null checks is turned off, the type system allows null and undefined to be assigned to any type. For example:
let name: string = null; // This is allowed when strict null checks is off
However, when strict null checks is enabled, the above code will result in a compilation error:
let name: string = null; // Error: Type 'null' is not assignable to type 'string'.
To enable strict null checks, you can set the `strictNullChecks` option to `true` in your `tsconfig.json` file:
{
"compilerOptions": {
"strictNullChecks": true
}
}
Here are some practical examples to illustrate how strict null checks work:
function greet(name: string | null) {
if (name) {
console.log(`Hello, ${name}`);
} else {
console.log("Hello, Guest");
}
}
interface User {
name: string;
age?: number; // age is optional
}
function printUser(user: User) {
console.log(`Name: ${user.name}`);
console.log(`Age: ${user.age ?? 'Not specified'}`); // Using nullish coalescing
}
In conclusion, enabling strict null checks in TypeScript is a best practice that leads to safer and more predictable code. By understanding how to work with null and undefined values effectively, developers can minimize errors and improve the overall quality of their applications.