Understanding TypeScript's Strict Null Checks: A Beginner's Guide to Avoiding Runtime Errors

Learn how TypeScript's strict null checks help you avoid runtime errors by ensuring variables aren't unexpectedly null or undefined.

If you’re new to TypeScript, you might encounter errors related to null or undefined values that cause bugs during runtime. TypeScript’s strict null checks feature is designed to help you catch these issues early by forcing you to handle null and undefined explicitly in your code.

When strict null checks are enabled, TypeScript won’t allow you to assign null or undefined to a variable unless you explicitly declare it as a union type with null or undefined. This helps prevent unexpected runtime errors like "Cannot read property '...' of null".

Here’s an example without strict null checks enabled:

typescript
function greet(name: string) {
  console.log("Hello, " + name.toUpperCase());
}

greet(null); // This compiles, but will throw an error at runtime.

In this case, `name` is expected to be a string, but we pass `null`, which compiles but causes a runtime error when trying to use `toUpperCase()` on `null`.

Now, let's enable strict null checks in the `tsconfig.json` file:

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

With strict null checks enabled, TypeScript will show an error if you try to pass `null` to a function that doesn't expect it.

To fix the above error, you can explicitly allow `null` as a valid type and handle it:

typescript
function greet(name: string | null) {
  if (name === null) {
    console.log("Hello, guest!");
  } else {
    console.log("Hello, " + name.toUpperCase());
  }
}

greet(null); // Output: Hello, guest!
greet("Alice"); // Output: Hello, ALICE

By explicitly checking for `null`, you protect your code from runtime errors and make it clear how `null` values are handled.

In summary, enabling `strictNullChecks` improves the safety of your TypeScript code by ensuring you consider `null` and `undefined` values upfront, helping you avoid common runtime errors caused by unexpected null values.

To enable this feature, make sure your `tsconfig.json` has the following setting: { "compilerOptions": { "strictNullChecks": true } }