Sub topic 15
Turn on strict mode step by step
This chapter assumes you have already renamed at least one file to .ts, you can read basic compiler errors, and you know what any, unknown, narrowing and null checks are from earlier chapters. Here you will switch on strict checking in stages. The goal is to avoid one change that produces thousands of errors.
What `strict` is
"strict": true is a shortcut that enables a family of separate flags. Each flag can also be set on its own. The ones that matter for a migration are:
| Flag | What it catches |
|---|---|
| `noImplicitAny` | Parameters and values whose type the compiler cannot infer and would silently make `any` |
| `strictNullChecks` | Using a value that might be `null` or `undefined` as if it were always present |
| `strictFunctionTypes` | Unsafe assignment of function parameters (parameter types are compared contravariantly) |
| `strictBindCallApply` | Wrong arguments passed to `bind`, `call` and `apply` |
| `strictPropertyInitialization` | Class properties that are declared but never assigned in the constructor |
| `noImplicitThis` | Using `this` where its type is implicitly `any` |
| `useUnknownInCatchVariables` | Treats `catch (e)` as `unknown` instead of `any` |
| `alwaysStrict` | Emits `"use strict"` and parses in strict mode |
New TypeScript releases sometimes add flags to the strict family. Upgrading the compiler can therefore produce new errors in a project that already has "strict": true. Pin the TypeScript version in package.json and upgrade it deliberately.
Why go in stages
Turning on strict in a large codebase can produce hundreds or thousands of errors at once. You cannot tell which ones matter, and the team stops being able to merge. Staging gives you a green build after every step. Each flag also has a different cost, so you can order them by value for effort.
A common order is:
- Start with
strict: falseand a passing build. - Enable
noImplicitAny. - Enable
strictNullChecks. - Enable the remaining flags one at a time.
- Replace the individual flags with
"strict": true.
Step 1: measure before you change anything
Use --noEmit so the compiler checks types without writing files. Pass a flag on the command line to try it out without editing tsconfig.json:
npx tsc --noEmit --noImplicitAny | grep -c "error TS"The command prints the number of error lines. Repeat it with each candidate flag (--strictNullChecks, --strictPropertyInitialization and so on) to learn which one is cheap and which one is expensive. Note that --strictPropertyInitialization only works when strictNullChecks is also on, so test it together with that flag.
To see which files are worst, group the errors by file:
npx tsc --noEmit --strictNullChecks | grep "error TS" | cut -d'(' -f1 | sort | uniq -c | sort -rnFiles with a few errors are good places to start. Files with a lot of errors may need to be tackled one at a time, or later.
Step 2: enable `noImplicitAny`
Edit tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": false,
"noImplicitAny": true
},
"include": ["src"]
}Notice that "strict": false stays in place. The individual flag overrides it. Fix the errors using the techniques from earlier chapters: annotate parameters, add interfaces, install @types packages, and use unknown when a value is truly unknown. Avoid fixing every error with : any. An explicit any passes this flag but gives you none of the benefit, and you will have to find it again later. A search for : any in your source is a useful progress measure.
Step 3: enable `strictNullChecks`
This flag usually produces the most errors, because JavaScript code freely passes around values that might be missing. Turn it on the same way:
{
"compilerOptions": {
"strict": false,
"noImplicitAny": true,
"strictNullChecks": true
}
}Typical fixes are narrowing with if, optional chaining (user?.email), a default with ??, or changing a return type to T | undefined so callers must handle the missing case. Avoid the non-null assertion (value!) as a bulk fix. It silences the compiler and moves the failure to runtime. Use it only where you can show that the value exists, and add a comment saying why.
Step 4: the remaining flags
Each of these usually produces few errors, so you can add them quickly.
strictPropertyInitialization flags class fields that may be undefined when read:
class Session {
token: string; // error: not definitely assigned in the constructor
user?: string; // fine: declared optional
constructor(token: string) {
this.token = token; // assigning here fixes the error
}
}If a framework assigns the field after construction, token!: string; tells the compiler you take responsibility. Use this rarely.
useUnknownInCatchVariables changes what you may do with a caught error:
function safeParse(text: string): unknown {
try {
return JSON.parse(text);
} catch (e) {
// e is unknown here, so narrow it before use
const message = e instanceof Error ? e.message : String(e);
throw new Error("Invalid JSON: " + message);
}
}strictFunctionTypes and strictBindCallApply mostly catch real mistakes, such as passing a callback that expects a narrower argument type than the caller supplies. Fix them by correcting the callback's parameter type rather than by casting.
Step 5: collapse to `strict: true`
When every flag passes on its own, replace the list:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": true
},
"include": ["src"]
}Run npx tsc --noEmit and confirm zero errors. From now on, new flags added to the strict family are picked up automatically when you upgrade TypeScript. If one flag is still too costly, keep "strict": true and add an override, for example "strictPropertyInitialization": false. Treat it as a tracked exception, with a comment or ticket to remove it.
Handling a large codebase
When one flag produces too many errors to fix in one pull request, use these tools:
- A second config. Create
tsconfig.strict.jsonwith"extends": "./tsconfig.json"and the new flag set. Run it in CI as an extra check on files you list in itsinclude. Grow that list as you fix files, so fixed files can never regress. // @ts-expect-errorabove a single known-bad line. Unlike// @ts-ignore, it reports an error when the line becomes valid, so stale suppressions are found and removed.// @ts-nocheckat the top of a.tsor checked.jsfile to skip it temporarily. Count these as debt.
Common mistakes
- Expecting
strict: trueto override specific flags placed after it. A specific flag always wins overstrict, in either order in the file. A forgotten"strictNullChecks": falsequietly disables checks. - Testing flags only in the editor. Editors may use a different
tsconfig.json. Treat the command linetsc --noEmitas the source of truth. - Forgetting test files. If tests live outside
include, they are not checked. Add them or give them their own config. - Counting errors but not suppressions. A clean build with 400
@ts-ignorecomments is not strict.
Exercise
Your project has "strict": false and 900 errors appear when you add --strictNullChecks. Describe a safe plan to reach "strict": true without blocking the team, and name the tool that stops fixed files from regressing.
Show answer
First enable noImplicitAny and fix it, since it is usually cheaper. For strictNullChecks, group the errors by file to find easy ones. Create tsconfig.strict.json that extends the main config, sets "strictNullChecks": true, and lists only the files that already pass in include. Run it in CI, and add files to the list as they are fixed so they cannot regress. When all files pass, move the flag into the main tsconfig.json, enable the remaining flags one at a time, and finally replace them with "strict": true. Use @ts-expect-error for temporary suppressions because it reports when they become unnecessary.
Exercise
In this tsconfig.json, is strictNullChecks on or off? Why?
{ "compilerOptions": { "strict": true, "strictNullChecks": false } }
Show answer
It is off. An individually set flag overrides the strict shortcut, so every other strict flag is on but null checking is disabled.