Course contentsShow
TypeScript
Lesson 7 of 1,7961. Why TypeScriptFree lesson

Catching Null and Undefined Errors

Static typing prevents the billion-dollar mistake by tracking nullability and requiring explicit handling.

Catching Null and Undefined Errors

You'll learn: How TypeScript's static typing prevents the infamous "billion-dollar mistake" by tracking when values might be null or undefined.

The Billion-Dollar Mistake

In dynamically typed languages, accessing a property on null or undefined causes a runtime crash—often in production, after users have already been affected. Tony Hoare, who invented null references, called this his "billion-dollar mistake" because of the countless bugs and system failures it has caused over decades.

TypeScript solves this by tracking nullability at compile-time. Instead of discovering null errors when your app crashes, TypeScript warns you before the code ever runs.

How It Works

When you enable strict null checking (which you should!), TypeScript treats null and undefined as separate types. If a value might be null, TypeScript forces you to acknowledge and handle that possibility before letting you use it.

Think of it like a safety inspector: Before you can climb a ladder, the inspector checks if it's sturdy. TypeScript is that inspector—it won't let you "climb" (access properties) on a value that might be null or undefined without first verifying it's safe.

Without TypeScript, you write code assuming values exist, and discover the problem when users report crashes. With TypeScript, the compiler says "Wait—this could be null. Handle that case first."

This means:

  • No more "Cannot read property 'x' of undefined" errors slipping into production
  • Your code explicitly shows when you've considered edge cases
  • Refactoring is safer because TypeScript tracks every place a null value could appear

Key Takeaway: TypeScript's static type system catches null and undefined errors at compile-time, preventing crashes before your code runs and forcing you to handle edge cases explicitly.