Back to Blog
Lesson 38 of the TypeScript: Typing JavaScript with Confidence course
TypeScriptAugust 25, 20264 min read

Enforcing Strict Null Checks in TypeScript for Reliable Code

Stop runtime crashes by enabling StrictNullChecks. Learn how to configure your TypeScript compiler to safely handle null and undefined values in your project.

TypeScriptConfigurationCompilerSafetyStrictNullChecks
Detailed view of programming code in a dark theme on a computer screen.

Previously in this course, we covered The Non-Null Assertion Operator: Safely Bypassing Null Checks to handle cases where we are certain a value exists. Today, we turn to the foundation of that safety: enabling strictNullChecks in your Understanding tsconfig.json: A Beginner's Guide to Configuration.

In standard JavaScript, null and undefined are effectively "invisible" to the runtime until your code crashes. TypeScript’s strictNullChecks flag changes the game by forcing you to acknowledge these values at compile time.

Why StrictNullChecks is Essential for Safety

By default (or if strictNullChecks is set to false), TypeScript assumes null and undefined are valid values for every type. You could assign null to a string variable, and the compiler wouldn't blink. This leads to the infamous "cannot read property of 'x' of undefined" errors that plague production applications.

When you enable strictNullChecks, null and undefined are removed from the domain of other types. A string is now only a string. If a variable might be null, it must be explicitly defined as string | null.

Enabling the Compiler Configuration

To enable this, locate your tsconfig.json file and add the following to your compilerOptions:

JSON
{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

If you have a large existing codebase, you might see hundreds of errors appear immediately. Don't panic—this is simply the compiler finally telling you about all the "hidden" potential crashes in your logic.

Resolving Null and Undefined Errors

Simple and minimalist image showcasing the word 'ERROR' on a white background.

Once enabled, you’ll likely see errors when accessing properties on objects that might be missing or calling methods on variables that might be null. The solution is to use Type Narrowing.

Here is how we might handle a potentially missing task title in our ongoing project:

TYPESCRIPT
interface Task {
  id: string;
  title: string | null;
}

function printTaskTitle(task: Task) {
  // Error: Object is possibly CE9178">'null'
  console.log(task.title.toUpperCase()); 

  // Fix: Narrow the type using a conditional check
  if (task.title !== null) {
    console.log(task.title.toUpperCase());
  } else {
    console.log("Task has no title");
  }
}

The Reliability Impact

Enabling this flag forces you to write defensive code. Instead of hoping an API response contains the data you expect, you build the logic to handle the absence of that data gracefully. This is a massive leap in code reliability.

Hands-on Exercise: Securing the API Client

In our task API client, find the function that retrieves a single task. Currently, you might be assuming the response always contains a valid Task object.

  1. Enable "strictNullChecks": true in your tsconfig.json.
  2. Locate your getTaskById(id: string) method.
  3. Update the return type to Promise<Task | null> to reflect that a task might not be found.
  4. Update the calling code to handle the null case using an if check before accessing properties.

Common Pitfalls

  • Over-using the Non-Null Assertion: Beginners often try to fix every error by adding ! to variables. Avoid this; it defeats the purpose of the check. Only use ! when you have a guarantee external to the type system that the value exists.
  • Assuming Optional Properties are Nullable: Remember that an optional property (e.g., description?: string) is automatically string | undefined. You don't need | null unless the value can explicitly be set to null by your backend.
  • Ignoring the "Strict" Family: strictNullChecks is part of the strict flag suite. Enabling "strict": true in tsconfig.json enables this and several other important checks (like noImplicitAny). It is highly recommended to use strict: true for all new projects.

FAQ

Q: Can I enable strict mode for only one file? A: No, compiler settings are project-wide.

Q: Will this break my existing JavaScript libraries? A: No. TypeScript applies these rules to your code and the types of the libraries you use. If a library has incomplete type definitions, you might see errors, but the runtime behavior of your app remains identical.

Q: Is null the same as undefined in TypeScript? A: They are distinct types. However, under strictNullChecks, they both must be explicitly included in your types if you intend to use them.

Recap

Team members presenting a project in a modern office setting with a focus on collaboration.

By enabling strictNullChecks, you move your code's safety checks from the browser console to your editor. This configuration ensures that you handle empty states explicitly, preventing runtime crashes and making your codebase significantly more robust.

Up next: Exhaustive Switch Statements — where we learn how to use the never type to ensure our logic covers every possible state in our task API.

Similar Posts