Sub topic 13
Turning strictNullChecks on in an existing project
This chapter assumes that you know basic TypeScript types, union types, interfaces, JavaScript null and undefined, and the purpose of tsconfig.json.
Turning on strictNullChecks changes the meaning of existing types. Before the option is enabled, TypeScript often allows null and undefined where a type such as string is expected. With the option enabled, a string is always expected to contain a string. A value that may be missing must say so:
let title: string = "Report";
let optionalTitle: string | undefined;Start with a baseline
Create a clean branch and run the current type check before changing configuration. Record the command and its result. This gives you a comparison point.
Then enable the option in tsconfig.json:
{
"compilerOptions": {
"strictNullChecks": true
}
}If the project already uses "strict": true, strictNullChecks is already enabled unless another setting overrides it. Check which configuration the build actually uses. A repository may have separate files for development, tests, and production.
Run the same type-check command again. Do not fix errors in random order. Group them by cause first.
| Error pattern | Usual cause | Typical repair |
|---|---|---|
| Type `undefined` is not assignable | A lookup or optional value was used directly | Check, narrow, or provide a default |
| Object is possibly `null` | An API can return no object | Add a guard or optional chaining |
| Property has no initializer | A class field may be read before assignment | Initialize it or assign it in every constructor path |
| Type `null` is not assignable | Old code relied on permissive null handling | Use a nullable union or remove the invalid value |
Migrate in small groups
A practical migration usually follows the data flow from boundaries toward application logic.
- Fix configuration and confirm which files the compiler checks.
- Fix shared types and function signatures.
- Handle values from APIs, databases, environment variables, and configuration files.
- Fix collection lookups and DOM operations.
- Fix class initialization and constructors.
- Re-run tests and the production build after each group.
For example, Map.get returns number | undefined, even when the map usually contains the requested key:
const prices = new Map<string, number>();
prices.set("book", 12);
const price = prices.get("book");
if (price === undefined) {
throw new Error("Price is missing");
}
console.log(price * 2);The check is part of the program's behavior. Do not silence the error just because the missing case seems unlikely.
Use temporary boundaries carefully
Large projects can migrate one package or directory at a time. Keep the main configuration strict and isolate legacy code behind small functions. A boundary function can validate input and return a reliable type to the rest of the application.
Avoid replacing errors with ! everywhere:
const element = document.querySelector("#app")!;The non-null assertion tells the compiler to trust you. It does not check the value at runtime. Prefer a real check when the element may be absent:
const element = document.querySelector("#app");
if (!(element instanceof HTMLElement)) {
throw new Error("The app element is missing");
}
element.hidden = false;If a temporary suppression is unavoidable, keep it local, explain why it is safe, and create a follow-up issue to remove it. A project-wide weakening of the compiler removes the evidence that guides the migration.
Exercise
Exercise
A project has strictNullChecks enabled. config.timeout has type number | undefined, but a function requires a number. What are two safe ways to repair the call?
Show answer
Check that config.timeout is defined before calling the function, or use config.timeout ?? 30 if 30 is the intended default.