strictNullChecks: Preventing Null and Undefined Errors
What you'll learn: How strictNullChecks makes null and undefined distinct types, catching one of JavaScript's most common runtime errors at compile time.
The Problem Without strictNullChecks
In JavaScript, null and undefined lurk everywhere. You might call a method on what you think is a string, only to discover it's actually null at runtime — crashing your application with the dreaded "Cannot read property of null" error.
By default (without strict or strictNullChecks), TypeScript allows null and undefined to be assigned to any type. A variable typed as string can secretly hold null, giving you false confidence.
How strictNullChecks Changes Everything
When you enable strictNullChecks in your tsconfig.json, TypeScript treats null and undefined as distinct, separate types that cannot be assigned to other types unless you explicitly allow it.
// With strictNullChecks enabled
let name: string = "Alice";
name = null; // ❌ Error: Type 'null' is not assignable to type 'string'
let age: number = 30;
age = undefined; // ❌ Error: Type 'undefined' is not assignable to type 'number'
If a value might be null or undefined, you must express that in the type:
let name: string | null = "Alice";
name = null; // ✅ OK now
let age: number | undefined = 30;
age = undefined; // ✅ OK now
Now TypeScript forces you to handle these cases before using the value:
function greet(name: string | null) {
// ❌ Error: Object is possibly 'null'
console.log(name.toUpperCase());
// ✅ Must check first
if (name !== null) {
console.log(name.toUpperCase());
}
}
Why This Matters
Think of strictNullChecks as a safety net that catches the billion-dollar mistake (Tony Hoare's term for null references). Instead of discovering null errors when users click a button, TypeScript catches them while you're still writing code.
Key Takeaway: strictNullChecks makes null and undefined separate types that can't sneak into other types, forcing you to explicitly handle their presence and eliminating an entire class of runtime crashes before they reach production.