Mental model
When TypeScript's strictNullChecks: true flag is disabled, null and undefined silently inhabit every domain type (string, User, number), disguising potential Cannot read properties of undefined runtime crashes behind green compilation. With strictNullChecks: true, null and undefined become distinct explicit members of union types (string | null | undefined), forcing your code to narrow uncertainty via TypeScript's control-flow analysis (if, ??, ?., custom is predicates, and asserts invariants) before dereferencing properties. Combined with noUncheckedIndexedAccess: true, compiler guarantees shift nullable bugs from production error logs cleanly to build time.
Theory
TypeScript's control-flow graph analyzes early returns, typeof / instanceof checks, in property probes, equality comparisons, and explicit never-throwing assertions across branches so downstream statements see narrowed non-nullable types automatically without redundant casts.
| Guard Mechanism | Signature / Operator | Eliminates 0 / "" / false? | Production Use Case |
|---|---|---|---|
Nullish Coalescing (??) | val ?? fallback | No (triggers only on null or undefined) | Preserving valid numeric 0, empty string "", or false flags safely |
Optional Chaining (?.) | user?.profile?.avatar | Short-circuits safely to undefined | Traversing nested nullable JSON payloads cleanly before fallback |
Type Predicate (val is T) | function isDefined<T>(x: T | null): x is T | Depends on body predicate (!== null && !== undefined) | Filtering arrays cleanly (arr.filter(isDefined))—automatic in TS 5.5+! |
Assertion Function (asserts) | function assertUser(x: unknown): asserts x is User | Throws immediately when false | Precondition validation at API/webhook ingress & test invariants |
TypeScript 5.5 Inferred Predicates, noUncheckedIndexedAccess, and Assertion Declarations
Starting in TypeScript 5.5, simple truthiness/equality callbacks such as items.filter((x) => x !== null && x !== undefined) automatically infer type predicates (x): x is NonNullable<T>, removing legacy boilerplate while keeping nested property narrowing crisp. One important syntactic subtlety applies to assertion functions: TypeScript requires asserts helper functions to carry an explicit type annotation declared as a function declaration (not inferred arrow expressions in older TS contexts without explicit annotation) so control-flow analysis can verify termination guarantees across the caller block. Likewise, enabling "noUncheckedIndexedAccess": true turns arr[0] and dict[key] from T into T | undefined, exposing off-by-one array reads and missing map lookups across parsers and RAG chunkers before runtime.
typescriptexport interface CitationMetadata {id: string;pageCount: number;snippet?: string | null;}export function isDefined<T>(value: T | null | undefined): value is T {return value !== null && value !== undefined;}// Explicit function signature is required so TS tracks control-flow narrowing afterwardexport function assertPresent<T>(value: T | null | undefined,label: string,): asserts value is T {if (value === null || value === undefined) {throw new Error(`Invariant failed: missing required '${label}'`);}}export function formatSnippetSummary(citations: Array<CitationMetadata | null>,firstIndex: number,): string {// With strictNullChecks + TS 5.5 inferred predicates, filtered is CitationMetadata[]const validCitations = citations.filter(isDefined);const target = validCitations[firstIndex];assertPresent(target, "targetCitation");// Preserve valid pageCount = 0 cleanly using ?? instead of ||const pages = target.pageCount ?? 1;const preview = target.snippet?.trim() ?? "(no preview)";return `[${target.id}] (${pages} pages): ${preview}`;}
Alternatives and trade-offs
- Strict Control-Flow Narrowing (
strictNullChecks+noUncheckedIndexedAccess): Catches nearly all undefined dereference and missing dictionary key bugs at compile time with zero runtime overhead; increases initial annotation effort around dynamicRecord<string, V>lookups and DOM element queries (document.querySelector(...)). - Non-Null Assertion Operator (
value!): Suppresses compiler warnings in one character while emitting zero runtime checks, frequently causing delayedTypeErrorfailures in production when upstream APIs change. Restrict!solely to rare cases where invariants are trivially visible on the previous line—or preferassertPresent(). - Option / Result Monads (
neverthrow,Effect): Replaces exceptions and| nullunions with explicit algebraic containers (Ok<T> | Err<E>) for rich railway error handling across complex business pipelines, at the cost of library ergonomics and conversion layers against standard Promises.
Failure modes and misconceptions
- Logical OR (
||) Swallowing Valid0,"", orfalseValues: Writingconst temperature = input.temp || 0.7silently overwrites explicit deterministictemp: 0with0.7! Always use nullish coalescing (??) when zero, empty string, orfalseare valid domain values. - Array
.filter(Boolean)Losing Static Narrowing Edge Cases: Filtering numbers or strings with.filter(Boolean)strips0and""at runtime and leaves types loosely typed in pre-5.5 TypeScript. Use explicitval !== null && val !== undefinedpredicates (isDefined). - Callback Closures Resetting Outer Variable Narrowing: Narrowing
let user: User | nullin anif (user)branch does not preserveUserinside an asynchronoussetTimeoutor nested callback unlessuserisconst, because TypeScript assumesletvariables might be reassigned before the callback invokes! Copy to aconstvariable before capturing inside closures. - Assuming Compile-Time Narrowing Validates Untrusted JSON Payloads: Marking
const payload = (await res.json()) as Usertells TypeScript a field is non-null without inspecting incoming wire bytes. Parse external network data through Zod/Valibot schemas first so TypeScript'sstrictNullChecksreflects verified runtime structure.
Decision scenario
Your Next.js AI workbench processes optional tool outputs (score: 0, citations?: Array<... | null>, user-editable prompts "") and suffers intermittent client TypeError crashes when indexing dictionary lookups or applying || default settings. Enable "strict": true (strictNullChecks: true) plus "noUncheckedIndexedAccess": true in tsconfig.json, ban non-null ! assertions via ESLint (@typescript-eslint/no-non-null-assertion), replace all || fallback chains on numeric/boolean config fields with ??, capture narrowed let variables into const before React hooks or async closures, and funnel all API JSON parsing through Zod validation paired with reusable assertPresent() domain guards.
Learning outcomes
- Explain how
strictNullChecksseparatesnull/undefinedinto explicit union members narrowed by control-flow analysis. - Eliminate false-falsy bugs cleanly by choosing
??over||on numeric, empty-string, and boolean values. - Author type-safe array filter predicates (
val is T) andassertsprecondition guards cleanly. - Understand closure narrowing resets on mutable
letbindings and enablenoUncheckedIndexedAccessfor safe indexing.
Trade-offs
Enforcing strictNullChecks and noUncheckedIndexedAccess adds explicit boundary guards on array indexing and optional API fields, paying back dramatically fewer undefined production crashes and self-documenting nullable invariants at zero runtime performance cost.