Course contentsShow
← TypeScript
Lesson 1625 of 1,79637. Migrating JavaScript to TypeScriptFree lesson

Null and Undefined Everywhere

Addressing strictNullChecks failures in code that assumed values were always defined.

Null and Undefined Everywhere

You'll learn: how to systematically address the wave of strictNullChecks failures that surface when migrating JavaScript code that assumed values were always present.

The Migration Wake-Up Call

When you enable strictNullChecks on a JavaScript codebase converted to TypeScript, you'll often see hundreds or thousands of errors. Your code assumed variables, object properties, and function returns always had values—but TypeScript now forces you to acknowledge reality: nulls and undefineds are everywhere.

In JavaScript, you may have written:

function getUserName(userId: string) {
  const user = findUserById(userId);
  return user.name.toUpperCase(); // Crashes if user is null!
}

With strictNullChecks, TypeScript screams: "What if findUserById returns null? What if user.name is undefined?"

The Core Problem

JavaScript code frequently relies on assumptions:

  • "This API always returns data"
  • "This property is always set by the constructor"
  • "This value can't be null because I checked it... somewhere earlier"

TypeScript with strictNullChecks challenges every single assumption. You must now handle these cases explicitly.

Systematic Approaches

1. Add null/undefined to types honestly:

function findUserById(id: string): User | null {
  // Reality: sometimes returns null
}

2. Guard before accessing:

const user = findUserById(userId);
if (user) {
  return user.name.toUpperCase();
}
return "Unknown";

3. Use optional chaining for deep paths:

return user?.name?.toUpperCase() ?? "Unknown";

4. Non-null assertions when you're certain (sparingly!):

const user = findUserById(adminId)!; // You know admin exists

The migration process means touching many files, adding guards, refactoring APIs, and occasionally discovering real bugs that were waiting to happen.

Key Takeaway: Migrating to strictNullChecks reveals how pervasively JavaScript code assumes values exist—address each case with guards, optional chaining, or honest union types to make the implicit explicit.