Sub topic 13
Turning strictNullChecks on in an existing project
This chapter covers how to enable strictNullChecks in a codebase that was written without it. It assumes you know the earlier material: nullable union types, narrowing, ?., ??, the ! operator, and the basics of tsconfig.json. It also assumes you can run tsc from the command line.
What the flag does and does not change
strictNullChecks affects only type checking. The JavaScript that tsc emits is identical with the flag on or off. That makes the migration low risk at runtime. The errors you fix are places where the old code could already crash or misbehave.
With the flag off, null and undefined are assignable to every type. The compiler treats them as members of every type's domain, so it never asks you to handle them. With the flag on, they are separate types, and every place that did not handle them becomes an error.
In a large codebase, flipping the flag can produce hundreds or thousands of errors at once. A single commit that fixes them all is hard to review. It also blocks every other branch until it merges. The goal of an incremental migration is to keep the main branch shippable the whole time and to stop new unsafe code from being added while you work.
Step 1: Measure the size of the problem
Before you change any configuration, run the compiler with the flag on and count the errors. The command line flag overrides tsconfig.json for that run.
npx tsc --noEmit --strictNullChecks | grep -c "error TS"To see which files hurt most, group the errors by file:
npx tsc --noEmit --strictNullChecks \
| grep "error TS" \
| cut -d'(' -f1 \
| sort | uniq -c | sort -rn | head -20The second command lists the 20 files with the most errors. Files with zero errors are the cheapest wins, and they often make up a large share of the project. A file that already uses ?. and explicit checks everywhere may need no changes at all.
Step 2: Choose a strategy
TypeScript has no per-file switch for strictNullChecks. The flag is a setting of the whole compilation, so every strategy works by choosing which files are in the compilation.
| Strategy | How it works | Trade-off |
|---|---|---|
| Flip and fix everything | Set the flag, fix all errors in one branch | Simple, but only practical for small projects |
| Second tsconfig | A strict config lists the migrated files; CI checks both configs | No extra tooling; you maintain a file list |
| Third-party plugin or script | Tools that check marked files under strict rules (for example `typescript-strict-plugin`) | Per-file granularity; adds a dependency |
| Strict for new code only | New packages in a monorepo start strict | Stops growth, but never finishes the old code |
The second tsconfig is the approach covered here because it needs only the compiler.
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strictNullChecks": true,
"noEmit": true
},
"include": [
"src/util/**/*.ts",
"src/models/**/*.ts"
]
}Save this as tsconfig.strictnull.json and run it with npx tsc -p tsconfig.strictnull.json. When a config extends another, its include replaces the base include instead of merging with it. So only the listed folders are the starting points of the check.
Step 3: Migrate from the leaves upward
Start with modules that import nothing from your own code, such as utilities, constants, and type definitions. Then move to the modules that import only those, and continue toward the application entry points. Each finished layer can then be imported by the next layer without dragging in unchecked code.
The CI rule matters most. Both configs must pass on every pull request. The strict file list then works as a ratchet: it only grows, and a migrated file can never regress without failing the build.
Step 4: Fix errors by changing types, not by silencing them
Most of the errors come from a few messages. Learning to read them speeds up the work.
| Error | Typical cause | Usual fix | Column |
|---|---|---|---|
| TS2322: Type 'X \ | undefined' is not assignable to type 'X' | A possibly missing value is stored in a non-nullable variable or field | Narrow first, or widen the destination type if absence is valid |
| TS18047: 'x' is possibly 'null' | Property access on a nullable value | Narrow, or use `?.` | |
| TS18048: 'x' is possibly 'undefined' | Same, with `undefined` | Narrow, or use `?.` | |
| TS2345: Argument of type 'X \ | undefined' is not assignable to parameter | Passing a nullable value to a required parameter | Check before the call, or make the parameter optional |
| TS2564: Property has no initializer | `strictPropertyInitialization` is part of `strict` and needs this flag | Initialize in the constructor, or use `!` with a reason |
The best fixes start where the value originates. If a function can return nothing, say so in its return type, and let the compiler show every caller that needs an update.
interface User {
id: number;
name: string;
}
// Before: the signature claimed a User, but find returns undefined on a miss.
// function findUser(users: User[], id: number): User { ... }
function findUser(users: User[], id: number): User | undefined {
return users.find((u) => u.id === id);
}
function greet(users: User[], id: number): string {
const user = findUser(users, id);
if (user === undefined) {
return "Hello, guest";
}
return `Hello, ${user.name}`;
}Correcting one return type produced one error in greet, and greet now handles the missing case. This is the pattern to aim for. A fix that corrects a type at its source removes many downstream errors at once, so fix the sources first and recount.
Look at the whole data flow
Some errors reveal that two parts of the program disagree about whether a value can be missing. Take care with these before choosing a fix:
- If a field is truly optional in the data, make it optional in the interface (
middleName?: string) and handle it where it is read. - If a field is always present once an object is built, but is filled in after construction, consider splitting the type into a "draft" and a "complete" version instead of marking everything optional.
- If the value comes from outside the program (JSON, a database,
localStorage), do not trust a type assertion. Validate it at the boundary and produce a properly typed value.
Step 5: Treat suppressions as debt
Sometimes a fix is too large for the current pull request. You have three tools, in order of preference:
- A real fix: narrowing, a default with
??, or a corrected type. - A non-null assertion
!with a comment that says why the value cannot be missing. - A
// @ts-expect-errorcomment with a tracking tag.
interface Config {
port?: number;
}
declare const config: Config;
// @ts-expect-error TODO(strictNull): port can be undefined in test setups
const port: number = config.port;@ts-expect-error is better than @ts-ignore because the compiler reports an error when the suppressed line no longer has a problem. Fixing the code therefore forces you to delete the comment.
Search the codebase for your tag to measure the remaining debt, and consider an ESLint rule such as @typescript-eslint/no-non-null-assertion to flag new ! usage in migrated folders.
Step 6: Watch for external types
Third-party type definitions can cause errors that you cannot fix in your own code. If an old @types package assumes nullable values everywhere, upgrade it first. If a package ships declarations that fail under the flag, skipLibCheck: true stops the compiler from checking .d.ts files. It hides errors inside declaration files, but your own code is still checked against those declarations.
Step 7: Flip the main switch
When the strict list covers every source file, move the setting into the main config and remove the second config.
{
"compilerOptions": {
"strictNullChecks": true
}
}If the project later adopts the full strict family, you do not have to take every option at once. Individual options override strict, so this configuration enables the family except for null checks:
{
"compilerOptions": {
"strict": true,
"strictNullChecks": false
}
}Note that strictPropertyInitialization requires strictNullChecks. With null checks off, the compiler reports a configuration error if you also turn it on. Teams that adopt strict first and enable null checks last must leave strictPropertyInitialization off until then.
Common mistakes during migration
- Sprinkling
!to reach zero errors quickly. The code then compiles, but it has the same crashes as before, and the type checker now reports that everything is fine. - Making every field optional to silence assignment errors. This spreads
undefinedchecks across the program and hides which values are truly required. - Replacing
||with??everywhere as a style change. The two differ for0,"", andfalse, so each change needs a decision. - Forgetting tests. Test files often build partial objects and pass
undefined. Include them in the strict list, or they will fail on the final flip. - Adding new unmigrated files to the project during the migration. Require new files to be added to the strict list from the start.
Exercise
A strict config includes src/orders/total.ts, which imports src/legacy/tax.ts. The strict run reports errors inside tax.ts even though tax.ts is not in the config's include. Why does this happen, and what is the best order of work?
Show answer
The compiler follows imports and adds every imported file to the program, so tax.ts is checked under strictNullChecks even though it is not listed. Migrate tax.ts first, because it is the dependency (the leaf), then add total.ts. In general, move bottom-up through the import graph.
Exercise
A function getTimeout(options) is declared to return number, but its body is return options.timeout; where timeout is optional. Under strictNullChecks the compiler reports TS2322. Name two valid fixes and say which one you would pick if callers can handle a missing timeout.
Show answer
Fix 1: change the return type to number | undefined so the signature matches the data, then fix callers as the compiler reports them. Fix 2: supply a default inside the function, for example return options.timeout ?? 30;, which keeps the return type number. If callers can handle a missing timeout, pick the first fix, since it keeps the information that no timeout was set. If every caller needs a number anyway, the default in one place is simpler.
Exercise
Why does the chapter recommend // @ts-expect-error over // @ts-ignore for temporary suppressions, and what problem appears when a file is checked under both a strict and a non-strict config?
Show answer
@ts-expect-error makes the compiler report an error once the suppressed line is fixed, so stale suppressions get removed. In the dual-config setup, the non-strict config does not produce the null error, so the directive is unused there and the base run fails with "Unused '@ts-expect-error' directive". The workaround is to use @ts-ignore while both configs check the file, or to add the suppressions when you flip the main flag.