FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Strict Null Checks & Type Narrowing

Strict null checks, nullish coalescing, optional chaining, type predicates, and assertions.

Freshness: current•14 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Enforce strict null safety across APIs
  • ✓Write custom type predicates and assertion functions
Full Technical Reference Document

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.

Nullable Union T
null
undefined
Control Flow Branching (if / ?? / ?.)
Custom Type Predicate (val is T)
Guaranteed Non-Null Type Narrowing
Conceptual teaching model synthesized from:typescript-54-spec,tc39-ecma262

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 MechanismSignature / OperatorEliminates 0 / "" / false?Production Use Case
Nullish Coalescing (??)val ?? fallbackNo (triggers only on null or undefined)Preserving valid numeric 0, empty string "", or false flags safely
Optional Chaining (?.)user?.profile?.avatarShort-circuits safely to undefinedTraversing nested nullable JSON payloads cleanly before fallback
Type Predicate (val is T)function isDefined<T>(x: T | null): x is TDepends 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 UserThrows immediately when falsePrecondition 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.

typescript
export 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 afterward
export 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 dynamic Record<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 delayed TypeError failures in production when upstream APIs change. Restrict ! solely to rare cases where invariants are trivially visible on the previous line—or prefer assertPresent().
  • Option / Result Monads (neverthrow, Effect): Replaces exceptions and | null unions 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

  1. Logical OR (||) Swallowing Valid 0, "", or false Values: Writing const temperature = input.temp || 0.7 silently overwrites explicit deterministic temp: 0 with 0.7! Always use nullish coalescing (??) when zero, empty string, or false are valid domain values.
  2. Array .filter(Boolean) Losing Static Narrowing Edge Cases: Filtering numbers or strings with .filter(Boolean) strips 0 and "" at runtime and leaves types loosely typed in pre-5.5 TypeScript. Use explicit val !== null && val !== undefined predicates (isDefined).
  3. Callback Closures Resetting Outer Variable Narrowing: Narrowing let user: User | null in an if (user) branch does not preserve User inside an asynchronous setTimeout or nested callback unless user is const, because TypeScript assumes let variables might be reassigned before the callback invokes! Copy to a const variable before capturing inside closures.
  4. Assuming Compile-Time Narrowing Validates Untrusted JSON Payloads: Marking const payload = (await res.json()) as User tells TypeScript a field is non-null without inspecting incoming wire bytes. Parse external network data through Zod/Valibot schemas first so TypeScript's strictNullChecks reflects verified runtime structure.
Reflect before revealing the guide

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 strictNullChecks separates null/undefined into 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) and asserts precondition guards cleanly.
  • Understand closure narrowing resets on mutable let bindings and enable noUncheckedIndexedAccess for 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.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.