Mastering TypeScript's Strict Null Checks for Safer Code

Learn how TypeScript's strict null checks help prevent common errors by catching null and undefined values early in your code.

TypeScript is a powerful tool that adds static typing to JavaScript, making your code more predictable and easier to debug. One feature that helps catch common bugs early is called strict null checks. This feature ensures that variables declared without a null or undefined type can't accidentally hold those values. Let's explore what strict null checks do and how to use them effectively.

By default, in JavaScript and non-strict TypeScript, variables can be null or undefined without much warning. For example:

typescript
let name: string = "Alice";
name = null; // No error here if strictNullChecks is off

This can lead to runtime errors if you try to use a variable that unexpectedly holds a null or undefined value. Enabling strict null checks in TypeScript prevents this by making `null` and `undefined` distinct types that variables must explicitly allow.

To enable strict null checks, add this line to your `tsconfig.json` file:

typescript
{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

With this option turned on, the previous example will cause a compile error because `name` is declared as a string and cannot be assigned `null`:

typescript
let name: string = "Alice";
name = null; // Error: Type 'null' is not assignable to type 'string'.

If you want a variable to accept null or undefined values, you must explicitly indicate this using union types. For example:

typescript
let name: string | null = "Alice";
name = null; // This is allowed now

This way, TypeScript forces you to handle these cases explicitly and catch potential null or undefined errors at compile time rather than at runtime.

When accessing properties or calling methods on variables that can be null or undefined, you need to perform checks to ensure safety. Here is an example using an optional chaining operator (`?.`) to safely access a property:

typescript
interface User {
  name: string;
  age?: number | null;
}

const user: User = { name: "Bob", age: null };

// Safe check for age
const userAge = user.age ?? 0; // Uses nullish coalescing to default to 0

console.log(userAge);

In summary, enabling strict null checks in TypeScript makes your code more robust by requiring you to explicitly deal with null and undefined values, preventing many common runtime errors.

To master strict null checks: - Enable `strictNullChecks` in your tsconfig. - Use union types (e.g., `string | null`) for nullable variables. - Use runtime checks or optional chaining before accessing potentially null or undefined values. - Leverage TypeScript’s compiler to catch mistakes early.

With these practices, your TypeScript code will be safer, cleaner, and easier to maintain.