C.W.K.
Stream
Lesson 03 of 05 · published

`strictNullChecks`

~7 min · strict-mode, strict-null-checks, null-safety

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Null is its own type. So is undefined. They don't sneak into other types unless you let them."

What it changes

Without strictNullChecks, null and undefined are assignable to every type. A string variable can secretly hold null. A function returning User can secretly return null. The type system says 'string' but the reality says 'string-or-null,' and the discrepancy hides every NullPointerException.

With the flag on, null and undefined are their own types. You must include them explicitly in any union that allows them. string | null accepts null; string doesn't. The type system finally tells the truth.

The cascade of fixes

Turning on strictNullChecks on a legacy codebase exposes every place that silently allowed null. The fixes fall into categories:

  • Make the type explicit: stringstring | null.
  • Narrow before use: if (x !== null) { ... use x as string ... }.
  • Use the non-null assertion ! when you know better than the compiler (sparingly).
  • Refactor to remove the nullability entirely.
strictNullChecks is the second-biggest impact strict flag after noImplicitAny. Combined, those two flags catch the vast majority of latent type unsafety in real codebases.

Code

Without and with strictNullChecks·typescript
// Without strictNullChecks — null hidden everywhere.
function getUser(id: number): User {
  return null;             // ✅ compiles — null assignable to User
}
const u = getUser(1);
console.log(u.name);        // crashes at runtime if null

// With strictNullChecks:
function getUserSafe(id: number): User | null {
  return null;             // ✅ — return type allows null explicitly
}
const u2 = getUserSafe(1);
// u2.name              // ❌ Object is possibly 'null'
if (u2 !== null) {
  u2.name;               // ✅ narrowed to User
}

// Or use optional chaining:
u2?.name;                 // string | undefined — safe access

External links

Exercise

Write a function whose declared return type is User. Have it actually return null on some path. With strictNullChecks off, this compiles silently. Turn it on — see the error appear. Fix it by either updating the return type or guarding the null case.
Hint
The flag forces honesty: if your function can return null, the type must say so. Most TypeScript bugs in pre-strict codebases trace back to this hidden discrepancy.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.