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

TypeScript strict null checks — handling nullable types

Submitted by: @anonymous··
0
Viewed 0 times
strictNullCheckspossibly nullpossibly undefinedoptional chainingnullish coalescing

Error Messages

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

Problem

After enabling strict or strictNullChecks, hundreds of TypeScript errors appear. Properties that were previously accessible now show 'Object is possibly null or undefined'.

Solution

This is correct — those were all potential runtime crashes. Fix strategies: (1) Optional chaining: obj?.prop?.nested. (2) Nullish coalescing: value ?? defaultValue. (3) Type guards: if (value !== null) { / value is narrowed / }. (4) Non-null assertion: value! — only when you are certain (avoid in most cases). (5) Define types accurately: use T | null explicitly. (6) Use required fields in interfaces, make optional fields explicit with ?. (7) For gradual migration: enable strictNullChecks and fix file-by-file using // @ts-expect-error temporarily.

Why

Without strictNullChecks, TypeScript assumes every type includes null and undefined implicitly. Enabling it makes the type system accurately model nullable values, catching real bugs.

Revisions (0)

No revisions yet.