← Back to libraryQuestion 223 of 468
🔷TypeScriptIntermediate

strictNullChecks — null vs undefined

📌 Definition:

With strictNullChecks on, null and undefined are NOT assignable to other types unless explicitly included, forcing you to handle 'no value' cases and preventing the classic 'cannot read property of undefined' crash.

📖 Detailed Explanation:

Without strictNullChecks, every type silently includes null/undefined and the compiler ignores null-access bugs. With it on, string does NOT accept null; you must write string | null | undefined and then narrow before use. This surfaces optional API fields, possibly-missing DOM elements, and array-find results (which return T | undefined). You handle them with narrowing (if (x)), optional chaining (x?.y), nullish coalescing (x ?? default), or non-null assertion (x!) when certain. undefined typically means 'not provided'; null means 'explicitly empty' — teams often standardize on one.

🔑 Key Points:
  • strictNullChecks: null/undefined not silently assignable
  • Forces handling optional fields, find() results, missing DOM
  • Handle via narrowing, ?., ?? or (carefully) !
  • Catches 'cannot read property of undefined' at compile time
🌍 Real-World Example:

arr.find(u => u.id === 5) is typed User | undefined under strictNullChecks, so the compiler forces const user = arr.find(...); if (user) { user.email } — preventing a crash when no match exists.

🎯 Scenario-Based Interview Question:

Why does enabling strictNullChecks suddenly flag const el = document.querySelector('#x'); el.click()?