Sub topic 8
Strict mode and why it changes your errors
This chapter assumes you can run npx tsc, read a diagnostic's file, line, column and code, and write basic annotations, interfaces and unions. The same code can pass or fail depending on your tsconfig.json, so you need to know which compiler options are active before you trust a clean build or interpret an error.
What `strict` actually is
"strict": true is a shortcut. It turns on a family of separate checks. Each check can also be set on its own, and an explicit setting overrides what strict implies.
| Flag | What it enforces | Typical diagnostic |
|---|---|---|
| `noImplicitAny` | Every value needs a type the compiler can infer or that you wrote | TS7006: Parameter 'a' implicitly has an 'any' type |
| `strictNullChecks` | `null` and `undefined` are separate types, not members of every type | TS18048: 'first' is possibly 'undefined' |
| `strictFunctionTypes` | Function parameters are compared contravariantly | TS2322 on an assignment between function types |
| `strictBindCallApply` | `bind`, `call` and `apply` check their arguments | TS2345 on `fn.call(...)` |
| `strictPropertyInitialization` | Class properties must be assigned in the constructor | TS2564: Property 'name' has no initializer |
| `noImplicitThis` | `this` must have a known type | TS2683: 'this' implicitly has type 'any' |
| `useUnknownInCatchVariables` | `catch (e)` gives `e` the type `unknown` | TS18046: 'e' is of type 'unknown' |
| `alwaysStrict` | Emits `"use strict"` and parses in strict mode | Syntax errors for sloppy-mode code |
Newer TypeScript versions sometimes add flags to the strict family, for example strictBuiltinIteratorReturn in 5.6. Upgrading the compiler can therefore produce new errors in a project that did not change. Read the release notes when you upgrade.
The same code under two configurations
This file is accepted when strict is off:
const names: string[] = ["ada", "alan"];
const first = names.find((n) => n.startsWith("a"));
console.log(first.length);With strict on, the compiler reports error TS18048: 'first' is possibly 'undefined'. The code did not change. strictNullChecks changed what find returns: without it, string | undefined collapses to string, because undefined is silently allowed everywhere. With it, the compiler is telling you about a real runtime crash when nothing matches.
A strict configuration looks like this:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"noEmit": true
},
"include": ["src"]
}When a diagnostic surprises you, open the tsconfig.json that applies to the file. In a monorepo, the file may be covered by a different config than the one at the repository root, or by one that uses extends. Run npx tsc --showConfig to print the merged result, which shows which options came from a parent config.
What each flag changes
noImplicitAny
Without a type annotation or an inferable type, a parameter becomes any, and any switches checking off for everything it touches.
function add(a, b) {
return a + b;
}$ npx tsc --noEmit --pretty false
src/math.ts(1,14): error TS7006: Parameter 'a' implicitly has an 'any' type.
src/math.ts(1,17): error TS7006: Parameter 'b' implicitly has an 'any' type.The fix is to write the types you meant: function add(a: number, b: number): number. Only the missing inference is reported. An explicit : any is allowed under this flag, because you chose it.
strictNullChecks
This flag produces the most errors in a migrating codebase. It affects assignments as well as property access:
const label: string = null;This reports TS2322: Type 'null' is not assignable to type 'string'. The two fixes are to widen the type (string | null) if null is a legitimate value, or to supply a real string. Narrowing for the "possibly undefined" case is covered in the next chapter.
strictPropertyInitialization
This flag depends on strictNullChecks. Turning it on without that flag is itself a configuration error.
class User {
name: string;
constructor(name: string) {
// forgot to assign this.name
}
}The compiler reports TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor. The correct fix is to assign it:
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}useUnknownInCatchVariables
Anything can be thrown in JavaScript, so a caught value is unknown, not any:
try {
JSON.parse("{");
} catch (error) {
if (error instanceof Error) {
console.log(error.message);
} else {
console.log("Unknown failure", error);
}
}Writing error.message directly reports TS18046: 'error' is of type 'unknown'. You must check what the value is before you use it.
Overrides and precedence
An explicit flag wins over strict, regardless of order in the file:
{
"compilerOptions": {
"strict": true,
"strictPropertyInitialization": false
}
}This enables every strict check except property initialization. You can also test a flag from the command line without editing the config. For example, npx tsc --noEmit --strictNullChecks false runs the project's config with that one flag overridden. Command-line flags take precedence over the config file, but only when you run tsc with no file arguments. If you list files on the command line, tsc ignores tsconfig.json entirely.
Failure modes when changing strictness
- A clean build under loose settings proves less than it seems. Many errors in a codebase simply are not reported, so a sudden jump in error count after enabling
strictreflects problems that were already present. - Editor and CI can disagree. The editor uses the nearest
tsconfig.jsonto each file. CI may run a different config. If the two differ, you see errors in one place and not the other. - Flags change the message, not only the count. Older TypeScript versions say
TS2532: Object is possibly 'undefined', while newer ones name the variable under TS18048. Search by code and by message text, and expect version differences. - Suppression hides the migration. Adding
!oras anyat every new error removes the check you just enabled. See the chapter on escape hatches.
Migrating an existing project
Enabling strict all at once on a large codebase can produce hundreds of errors. A staged approach works better:
- Start with
strict: falseand make sure the build is clean. - Enable
noImplicitAny. Fix the untyped parameters, which are usually quick. - Enable
strictNullChecks. This is the largest step. Fix module by module, starting with files that have no dependencies on others. - Enable the remaining flags one by one, then replace the individual flags with
"strict": true. - Commit after each step so a regression can be traced to the flag that exposed it.
For new projects, start with strict: true. It is much cheaper to write code that satisfies the checks from the beginning than to retrofit it.
Exercise
A teammate enables "strict": true in tsconfig.json and then sets "strictNullChecks": false. A class property id: number; has no initializer. Does the compiler report TS2564 for it? Explain.
Show answer
No error appears for the intended reason, but not because the property is fine. strictPropertyInitialization requires strictNullChecks. Explicit flags override strict, so with strictNullChecks set to false the initialization check cannot work properly, and the compiler reports a configuration error about the option dependency. The fix is to re-enable strictNullChecks, or to disable strictPropertyInitialization deliberately and accept that uninitialized properties are not checked.
Exercise
This code compiles with strict off. Name the flag responsible and the error code you will see after enabling it. const first = ["a"].find((x) => x === "b"); console.log(first.length);
Show answer
strictNullChecks. The compiler reports TS18048: 'first' is possibly 'undefined', because find returns string | undefined when nothing matches.