What does the 'strictNullChecks' compiler option change about how null and undefined are treated?
Short answer
Without strictNullChecks, null and undefined are silently assignable to EVERY type (a major source of runtime errors). With it enabled, null and undefined become distinct types that must be explicitly included in a type's union (e.g.
Advertisement
AModel answer
Without strictNullChecks, null and undefined are silently assignable to EVERY type (a major source of runtime errors). With it enabled, null and undefined become distinct types that must be explicitly included in a type's union (e.g. `string | null`) before a variable can hold them — the compiler then forces you to check for them before use.
// Without strictNullChecks
let name: string = null; // allowed, but risky
// With strictNullChecks: true
// let name: string = null; // Error: 'null' not assignable to 'string'
let name2: string | null = null; // must be explicitReal-world example
Catching an entire category of 'Cannot read property of undefined' runtime errors at compile time instead of in production.
Likely follow-ups
- Why is strictNullChecks considered one of the single most valuable strict-mode flags to enable?
Related topics