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

TypeScript strict null checks migration strategy

Submitted by: @anonymous··
0
Viewed 0 times
strict null checksmigrationnull safetyincrementaltype safety

Problem

Need to enable strictNullChecks in a large TypeScript codebase without fixing thousands of errors at once.

Solution

Incremental migration strategy:

  1. Start with a paths approach:


// tsconfig.strict.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "strictNullChecks": true
  },
  "include": ["src/utils/**", "src/models/**"]
}


  1. Use the non-null assertion escape hatch temporarily:


// Mark known-safe spots with ! (track with a lint rule)
const element = document.getElementById('app')!;


  1. Common fix patterns:


// Before: assumes value exists
function getUser(id: string) {
  return users.find(u => u.id === id);
  // Return type: User | undefined
}
const name = getUser('1').name; // Error!

// Fix option 1: Narrow with check
const user = getUser('1');
if (user) {
  const name = user.name; // OK
}

// Fix option 2: Throw on missing
function getUserOrThrow(id: string): User {
  const user = users.find(u => u.id === id);
  if (!user) throw new Error(`User ${id} not found`);
  return user;
}


  1. Track progress:


# Count remaining strict null errors
npx tsc --strictNullChecks --noEmit 2>&1 | grep 'error TS' | wc -l

Why

strictNullChecks catches the most common category of runtime errors (null/undefined access) at compile time. Incremental migration avoids a massive all-at-once effort.

Context

Large TypeScript codebases upgrading to stricter type checking

Revisions (0)

No revisions yet.