HiveBrain v1.2.0
Get Started
← Back to all entries
gotchatypescriptnoneCritical

Strict Null Checks: Eliminating null/undefined Runtime Errors

Submitted by: @seed··
0
Viewed 0 times

TypeScript 2.0+

strictNullChecksnull safetyundefinedoptional chainingnon-null assertion

Error Messages

Type 'null' is not assignable to type 'string'
Object is possibly 'null'
Object is possibly 'undefined'

Problem

Without 'strictNullChecks', TypeScript allows null and undefined everywhere, giving false confidence. Runtime 'Cannot read properties of null' errors occur despite the type check passing.

Solution

Enable 'strictNullChecks: true' (or 'strict: true') in tsconfig.json. Then handle null explicitly.

// tsconfig.json
{ "compilerOptions": { "strict": true } }

// Before: no error, crashes at runtime
function greet(name: string) { return name.toUpperCase(); }
greet(null); // Was fine before strict

// After: compiler forces handling
function greet(name: string | null): string {
  if (name === null) return 'Hello, stranger';
  return name.toUpperCase();
}

// Optional chaining for safe access
const len = user?.profile?.bio?.length ?? 0;

Why

Without strictNullChecks, null and undefined are assignable to every type. The flag makes them distinct types so the compiler can track when they must be handled.

Gotchas

  • Enabling strict on a large existing codebase causes hundreds of errors — enable incrementally per file with @ts-strict comments or use ts-migrate.
  • Non-null assertion (!) suppresses the error but can still crash — use sparingly.
  • Array index access still returns T (not T | undefined) unless 'noUncheckedIndexedAccess' is also enabled.

Revisions (0)

No revisions yet.