Sub topic 15
Moving an Existing Project to Strict Mode
This chapter assumes you can read a tsconfig.json, you know what "strict": true bundles, and you can run npx tsc in a Node.js project. It covers how to adopt strict mode in a codebase that already compiles without it.
Why migrate in steps
Turning on "strict": true in a large JavaScript-flavored codebase can produce hundreds or thousands of errors at once. A change that size blocks every other pull request and is hard to review. A staged migration keeps the main branch green, spreads the work across several small pull requests, and lets the team merge fixes while normal feature work continues.
The plan has four parts:
- Measure the size of the problem.
- Enable
strictbut switch off the flags you are not ready for. - Re-enable the flags one at a time, fixing errors for each.
- Lock in the gains so that errors cannot come back.
Step 1: Measure
Before you change any file, find out how bad it is. The --strict command-line option overrides the file for this one run, so nothing on disk changes.
npx tsc --noEmit --strict | grep -c "error TS"To see which flag causes each error, run the same command once per flag. For example, npx tsc --noEmit --noImplicitAny and npx tsc --noEmit --strictNullChecks give separate counts. Write the numbers down. They tell you which flags to tackle first and give you a way to show progress.
Step 2: Enable strict with exceptions
The baseline configuration turns on the umbrella option and then switches off the flags that produce the most errors.
{
"compilerOptions": {
"strict": true,
"noImplicitAny": false,
"strictNullChecks": false
}
}An explicit setting always wins over the umbrella, whatever the order in the file. This means new strict flags that TypeScript adds in later releases are enabled for you, except for the ones you have pinned off.
There is a dependency to know about. strictPropertyInitialization requires strictNullChecks. If you turn off strictNullChecks and leave the first one on, tsc reports an option error (TS5052) instead of checking your code. Turn both off together:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": false,
"strictNullChecks": false,
"strictPropertyInitialization": false
}
}Step 3: Re-enable flags in order of effort
Do the cheap flags first. Each one removes a category of problems and builds momentum.
| Order | Flag | Typical effort | Typical fix |
|---|---|---|---|
| 1 | `alwaysStrict` | Very low | Usually none, since modules are already strict |
| 2 | `noImplicitThis` | Low | Add a `this` parameter to the function |
| 3 | `strictBindCallApply` | Low | Fix wrong argument types in `call` and `bind` |
| 4 | `strictFunctionTypes` | Low to medium | Fix callback parameter types |
| 5 | `useUnknownInCatchVariables` | Low | Narrow with `instanceof Error` |
| 6 | `noImplicitAny` | High | Add annotations |
| 7 | `strictNullChecks` | Highest | Add null checks and fix types |
| 8 | `strictPropertyInitialization` | Medium | Initialize fields or mark them optional |
Remove one override line, run npx tsc --noEmit, fix every error, and merge. Then move to the next flag.
Fixing noImplicitAny errors
The usual fixes are to annotate parameters, return types, and empty collections. A parameter with no annotation, such as function double(x), becomes function doubleTyped(x: number): number. The empty-array case is common and easy to miss:
const names = [];
names.push("Ada");
const typedNames: string[] = [];
typedNames.push("Ada");Under noImplicitAny, reading names after later pushes can fail because the compiler cannot decide its element type. An annotation on the declaration fixes it. When you truly do not know a type, use unknown rather than any. unknown forces you to narrow the value before using it, so the uncertainty stays visible.
Fixing strictNullChecks errors
This flag usually produces the most errors, and the most bugs found. Resist the urge to silence it with the non-null assertion !. Prefer a real check:
function lengthOf(text: string | null): number {
return text === null ? 0 : text.length;
}
function firstWord(text: string | undefined): string {
return text?.split(" ")[0] ?? "";
}Optional chaining (?.) and nullish coalescing (??) handle most cases in one line. The ! operator tells the compiler to stop checking, so reserve it for cases where a runtime guarantee exists that the compiler cannot see. Add a comment explaining that guarantee.
Handling errors you cannot fix yet
Sometimes one error is not worth fixing today. Use @ts-expect-error with a reason, not @ts-ignore:
declare function legacyParse(input: string): object;
// @ts-expect-error TODO(TEAM-123): legacy API accepts null, remove after refactor
const result = legacyParse(null);
console.log(result);The difference matters. @ts-ignore suppresses errors forever, even after the problem is fixed. @ts-expect-error produces its own error when the line stops failing, so stale suppressions get found and removed. You can also count them with grep to track remaining debt.
Strictness by directory
For a large repository, you can enforce strict mode only on migrated code. Create a second configuration that extends the main one and lists only the clean directories.
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strict": true,
"noEmit": true
},
"include": ["src/billing", "src/auth"]
}Save it as tsconfig.strict.json and run npx tsc -p tsconfig.strict.json. Because this file sets strict: true after extending, any override flags in the base file still apply unless you repeat them here. Set the specific flags to true in this file to be explicit.
Locking in the gains
A migration is only done when it cannot regress. Do these things:
- Run
npx tsc --noEmitin CI on every pull request, and make it a required check. - When a directory passes the strict config, add it to
include. Add a CI step fortsconfig.strict.jsonso that clean folders stay clean. - Each time a flag override is removed from the main file, never add it back. Reviewers should treat a new
falseoverride as a red flag. - When all overrides are gone, delete
tsconfig.strict.jsonand keep onetsconfig.jsonwith"strict": true.
Use npx tsc --showConfig to confirm what the compiler actually sees after extends and overrides are merged.
Common mistakes
- Enabling
noImplicitAnyfirst. It generates the most noise in untyped code, and many of its errors disappear naturally once you have typed the inputs. Start with the cheap flags. - Fixing errors with
anycasts.as anyclears the error and also removes the safety you are migrating for. Useunknownor a real type. - Mixing migration and feature work in the same pull request. Keep the diffs separate so reviewers can check that the migration only changes types and guards.
- Forgetting third-party types. If a library has no types, install
@types/...before adding your own declarations, and check thatskipLibCheckis not hiding problems in your own.d.tsfiles.
Exercise
A team sets "strict": true and "strictNullChecks": false, but leaves strictPropertyInitialization at its default. What happens when they run tsc, and what is the fix?
Show answer
The compiler reports an option error (TS5052) because strictPropertyInitialization cannot be used without strictNullChecks. The fix is to set "strictPropertyInitialization": false alongside strictNullChecks, then re-enable both together, with strictNullChecks first or in the same change.
Exercise
Why is // @ts-expect-error a better migration tool than // @ts-ignore, and why does a strict-only tsconfig sometimes report errors in folders you did not include?
Show answer
@ts-expect-error raises an error when the next line no longer has a problem, so outdated suppressions are found and deleted, while @ts-ignore stays silent forever. Files in include are only the roots. Any file they import is pulled into the compilation and checked with the same strict settings, so errors can appear in unmigrated imported files.