Migrating an existing TypeScript codebase to strict mode is one of those tasks that sounds straightforward until you run strict: true for the first time and watch your error count jump from zero to several thousand. In my experience leading this migration on two medium-sized codebases — one around 80k lines and another closer to 250k — the technical work is actually the easy part. The real challenge is sequencing the fixes so your team can keep shipping while the type system gets progressively stronger. This article lays out the step-by-step approach I now use by default, the order in which to enable flags, and the pragmatic trade-offs that keep the migration from stalling.
Strict mode is not a single check. It is a bundle of compiler options that together close most of the soundness holes that make TypeScript feel permissive by default. When you enable it without a plan, the errors overlap and it becomes hard to see which category needs attention first. An incremental, file-by-file or flag-by-flag strategy lets you isolate each type of unsoundness, fix it with the right pattern rather than a quick assertion, and lock in progress so you don't regress. What follows reflects what has actually worked on teams with ongoing feature work, not a greenfield setup where you can turn everything on from day one.
Decoding What strict Mode Actually Turns On Under the Hood
Before changing anything, it helps to be precise about what strict enables. As of TypeScript 5.x, setting "strict": true in your tsconfig.json is shorthand for eight separate flags. You can verify this in the compiler options documentation, but I find teams often assume it is just strictNullChecks and noImplicitAny. In practice, the other flags catch subtle runtime failures around this binding, incomplete control flow, and unsafe property access on abstract classes.
Understanding each flag individually matters because you will enable them one at a time during the migration. Some, like alwaysStrict, have almost no impact on an existing codebase that already uses ES modules. Others, like strictNullChecks, will touch nearly every file that interacts with the DOM, API responses, or optional configuration.
| Flag Enabled by strict | What It Catches | Typical Error Volume on Migration |
|---|---|---|
strictNullChecks |
Potential null and undefined values flowing into places that expect a defined value |
Very High — often 60-80% of total errors |
noImplicitAny |
Parameters and variables where the compiler would silently infer any |
High — concentrated in utility functions and untyped callbacks |
strictFunctionTypes |
Unsafe bivariant function parameter comparisons | Medium — appears in event handlers and higher-order functions |
strictBindCallApply |
Incorrect argument types when using bind, call, or apply |
Low — but critical for typed utility libraries |
strictPropertyInitialization |
Class properties declared without initialization or definite assignment | Medium — common in ORM models and Angular/React class components |
noImplicitThis |
this with an implicit any type inside functions |
Low to Medium — frequent in legacy JavaScript converted files |
Two flags not shown in that table — useUnknownInCatchVariables and alwaysStrict — are also part of the bundle but tend to produce fewer errors. The distinction is important for planning: I typically schedule strictNullChecks and noImplicitAny as dedicated sprints or focus weeks, while the remaining flags can often be fixed in a single pass by one engineer. If you want a deeper reference on how JavaScript's strict mode semantics relate to these checks, the MDN Web Docs on strict mode provides useful context on why the runtime and the type system both need stricter defaults.
Establishing a Baseline: Auditing Failures Before You Fix Anything
The worst way to start is to flip strict: true and try to fix errors in the editor as they appear. You lose any sense of scope, and you cannot measure progress. Instead, I start with a clean audit that writes the full error output to a file I can analyze offline.
Generating a Countable Error Inventory
Create a separate tsconfig for auditing that extends your base config but overrides strictness. This leaves your main build untouched for CI while you measure.
// tsconfig.strict-audit.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strict": true,
"noEmit": true,
"skipLibCheck": true
},
"exclude": ["node_modules", "dist"]
}
Then run npx tsc -p tsconfig.strict-audit.json --noEmit 2> strict-errors.txt and count the lines. In my last migration, that file contained 3,842 errors. Breaking it down with a simple script that groups by error code (TS2345, TS2322, TS2531, etc.) told us that TS2531: Object is possibly 'null' and TS2532: Object is possibly 'undefined' accounted for 2,711 of them. That single data point set the priority for the next month.
Prioritizing by Error Code, Not by File
It is tempting to go file-by-file alphabetically, but grouping by error type teaches you the repeatable fix pattern faster. If 200 errors are all TS7006: Parameter 'x' implicitly has an 'any' type, you can decide once how to type those parameters — often by extracting a shared type or enabling noImplicitAny with explicit annotations — and apply it consistently. File-by-file work, by contrast, forces you to context-switch between null checks, implicit any, and property initialization in the same pull request, which makes code review much harder.
At this stage I also tag files that are auto-generated or vendored and exclude them from the audit. There is no value in fixing strict errors in generated GraphQL types or Swagger clients; instead, fix the generator configuration or add a dedicated exclude entry and document why.
Isolating Migration Risk With Incremental tsconfig Inheritance
Once you know the scale of the problem, you need a mechanism that lets you enable strict checks for part of the codebase while the rest remains on the old settings. TypeScript's project references and config inheritance make this practical without resorting to // @ts-ignore scattered everywhere.
The Two-Config Pattern That Keeps CI Green
The approach I have found most sustainable is to keep tsconfig.json strict, and create a tsconfig.loose.json that relaxes the flags for unmigrated code. Or invert it, depending on your starting point. The key is that CI builds against the strict config with a list of excluded files that shrinks over time.
// tsconfig.json (target state - strict)
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"strictBindCallApply": true,
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler"
},
"include": ["src/**/*"]
}
// tsconfig.migration.json (transitional - used in CI until migration completes)
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strict": false,
"noImplicitAny": false,
"strictNullChecks": false
},
"exclude": [
"src/legacy/reporting/**/*",
"src/legacy/importers/**/*"
]
}
This is where TypeScript Project References for Monorepos: Build Performance and Module Boundaries becomes directly relevant. If your repository is already split into packages or project references, you can enable strict mode one package at a time by overriding the compiler options per reference. That is significantly cleaner than maintaining a long exclusion list in a single config. I've used this to migrate shared utility packages first — they have the highest leverage — then move outward to application code that depends on them.
Using expect-error Instead of ignore for Temporary Suppressions
When you must suppress an error to keep the build green during migration, prefer // @ts-expect-error over // @ts-ignore. The difference matters: expect-error will itself become an error once the underlying issue is fixed, which prevents stale suppressions from lingering forever. I enforce this with an ESLint rule (@typescript-eslint/ban-ts-comment) that disallows ts-ignore entirely. Each suppression should also include a tracking ticket reference so it does not become permanent tech debt.
Confronting strictNullChecks: The Source of 80% of Your Errors
There is a reason strictNullChecks deserves its own section. In every migration I have participated in, it dominates the error count and it forces you to make real decisions about your domain model, not just add type annotations. The compiler is now telling you that every value that could be null or undefined must be handled explicitly.
The most common patterns I see failing are: DOM lookups (document.getElementById returns HTMLElement | null), optional API fields, map lookups (Map.get returns T | undefined), and array access (arr[0] is T | undefined under strict checks with noUncheckedIndexedAccess). Each of these has a correct fix that is not simply adding !.
Replacing Non-Null Assertions With Narrowing and Guards
When engineers are under pressure to clear hundreds of errors, the non-null assertion operator (!) is the fastest escape hatch. I've found that allowing it without review undoes much of the value of strict mode. In our migration, we limited ! to test files and two narrowly defined production cases, and required an explanatory comment for each use. Everywhere else, we used one of three alternatives.
// Before - fails under strictNullChecks
function getUserName(userId: string) {
const user = userMap.get(userId);
return user.name; // TS2532: Object is possibly 'undefined'
}
// After - explicit narrowing with early return
function getUserName(userId: string): string | null {
const user = userMap.get(userId);
if (!user) {
return null;
}
return user.name;
}
// Alternative - assertion function for places where absence is truly exceptional
function assertUserExists(user: User | undefined): asserts user is User {
if (!user) {
throw new Error("Expected user to exist - invariant violated");
}
}
function getUserNameOrThrow(userId: string): string {
const user = userMap.get(userId);
assertUserExists(user);
return user.name; // narrowed to User, no assertion operator needed
}
For cases where null and undefined have distinct meanings — for example, an API that returns null for "explicitly cleared" versus undefined for "never set" — discriminated unions are a far safer model than optional properties. I often point teams to Discriminated Unions in TypeScript: Modeling Domain Logic Safely when refactoring these API boundary types, because representing the states explicitly makes the null handling self-documenting and eliminates whole classes of conditional checks.
Handling External Data and API Boundaries
Strict null checks quickly expose the gap between what your API types claim and what the server actually sends. If your types say a field is string but the server occasionally omits it, you have been relying on runtime luck. The fix is not to make everything optional to silence the compiler; it is to validate at the boundary and then trust the validated type internally.
This is where runtime validation pays for itself. Rather than defensively checking for undefined deep in business logic, validate once when data enters the system and narrow to a strict internal type. My current preference is to combine strict mode with schema validation at fetch boundaries, which is covered in detail in Runtime Type Validation with Zod: Bridging TypeScript and External Data. Even a lightweight validator that just strips unknown keys and coerces missing optionals gives strict null checks a solid foundation to build on.
Closing the Gaps on noImplicitAny and Strict Function Checks
Once null checks are under control, the next largest category is usually noImplicitAny. These errors are less conceptually difficult but they require discipline to fix well. The compiler is simply refusing to infer any when it cannot determine a type.
The typical culprits are untyped callback parameters, empty array literals without a type argument, and utility functions that were written before generics were widely used in the codebase. Fixing them often reveals a missing shared type that should have existed from the start.
Typing Untyped Boundaries Without Over-Annotating
Not every fix requires an explicit type annotation on every variable. In many cases, giving the compiler one well-placed generic constraint or return type is enough for it to infer the rest.
// Before - noImplicitAny errors on both arr and predicate
function filterAsync(arr, predicate) {
return Promise.all(arr.map(predicate)).then(results => arr.filter((_, i) => results[i]));
}
// After - minimal annotations, compiler infers the rest
async function filterAsync<T>(
arr: T[],
predicate: (item: T) => Promise<boolean>
): Promise<T[]> {
const results = await Promise.all(arr.map(predicate));
return arr.filter((_, i) => results[i]);
}
For cases where you need to work with truly dynamic data — such as a plugin system or a thin wrapper around JSON.parse — use unknown instead of any. The unknown type forces callers to narrow before use, which is exactly the behavior you want under strict mode. If you find yourself reaching for any to make a utility function flexible, that is usually a sign you need a generic. The patterns in TypeScript Generics: Practical Examples Beyond the Basics cover this transition from any to properly constrained generics, and TypeScript Utility Types: Pick, Omit, Partial and Record Explained is a useful companion when you need to derive strict types from existing domain models without duplicating definitions.
Addressing strictFunctionTypes and strictBindCallApply Together
These two flags rarely produce many errors, but the ones they do produce are often subtle. strictFunctionTypes catches cases where a handler that expects a more specific type is assigned to a slot that provides a more general one — classic in event emitter patterns. strictBindCallApply catches mismatched arguments when you use call or apply with a typed function. I've found that both are best fixed by tightening the function signatures rather than loosening the assignment. If a callback truly must handle a union type, make that explicit in its parameter type rather than relying on bivariance to hide the mismatch.
Locking In Strict Mode So It Never Regresses
The final phase is not about fixing errors but about preventing new ones. I have seen teams complete a strict migration and then slowly accumulate non-strict files again because there was no enforcement mechanism. The migration is only complete when the default for every new file is strict.
First, make the strict config the default. Remove the transitional loose config and ensure tsconfig.json has "strict": true without overrides. Second, add a CI check that fails if any file introduces a // @ts-ignore or widens a type to any without an unknown narrowing path. A simple grep in CI — if grep -r "ts-ignore" src/; then exit 1; fi — catches the most common regression. More sophisticated setups use the typescript-eslint rules no-explicit-any and no-unsafe-assignment to flag new any usage at lint time.
Third, document the patterns your team agreed on for handling nulls, uninitialized properties, and generic constraints. A short internal decision log that shows "we use assertion functions for invariants, early returns for expected absences, and Zod schemas at API boundaries" prevents each engineer from inventing their own approach. In my experience, the migration PRs themselves serve as the best documentation if you link them from a central handbook page.
Finally, schedule a follow-up audit after one or two release cycles. Run the same tsc --noEmit audit you started with and confirm the error count remains at zero. If you are working with data that comes from outside TypeScript — configuration files, JSON payloads, or environment variables — consider adding a periodic validation step that checks those sources against the strict types you now enforce. The IETF RFC Standards are a helpful reference when those payloads involve URL handling, date formats, or HTTP semantics where the specification is stricter than what loose types previously allowed.
Frequently Asked Questions
Should I enable all strict flags at once or one at a time?
Enable one flag at a time in order of impact. Start with strictNullChecks because it produces the most errors and has the greatest runtime safety benefit, then tackle noImplicitAny, and finally enable the remaining flags together. Enabling everything at once makes it difficult to group errors by pattern and leads to inconsistent fixes, especially non-null assertions applied everywhere just to clear the error count.
Is it acceptable to use the non-null assertion operator (!) during migration?
Use it sparingly and only when you can prove the value is non-null through an invariant that the compiler cannot see, such as a framework guarantee that a DOM element exists after a specific lifecycle hook. In my experience, most uses of ! during a migration can be replaced with an early return, an assertion function, or a runtime check. Treat each ! as tech debt that requires a comment explaining why narrowing was not possible.
How do I handle third-party libraries that are not strict-compatible?
Leave skipLibCheck: true enabled so errors in declaration files do not block your migration. If a library ships without types or with loose types, write a thin wrapper module with strict types and validate inputs at the wrapper boundary rather than adding any throughout your codebase. For declaration files you control, add strict types incrementally and contribute them back via DefinitelyTyped when the library is open source.
What is the best way to keep the migration from blocking feature work?
Use an incremental config setup — either exclusion lists or project references — so only migrated files are checked strictly in CI. Assign ownership of unmigrated directories to specific teams or sprints, and make strict compliance a requirement for any new file. This lets feature work continue in unmigrated areas while steadily shrinking the loose surface area. In a codebase with active parallel development, I have found that migrating shared utilities and types first provides the most leverage for the least disruption.