patterntypescriptMajorpending
TypeScript strict null checks migration strategy
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:
- Start with a paths approach:
// tsconfig.strict.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strictNullChecks": true
},
"include": ["src/utils/**", "src/models/**"]
}- Use the non-null assertion escape hatch temporarily:
// Mark known-safe spots with ! (track with a lint rule)
const element = document.getElementById('app')!;- 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;
}- Track progress:
# Count remaining strict null errors
npx tsc --strictNullChecks --noEmit 2>&1 | grep 'error TS' | wc -lWhy
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.