Sub topic 8
Turning on strict mode
This chapter assumes you can already compile a project with tsc and that you have a tsconfig.json with target, module, outDir, rootDir, and include. Here you will learn what the strict option does, how its individual flags change what the compiler accepts, and how to adopt it in an existing codebase without stopping all other work.
What `strict` actually is
strict is an umbrella option. Setting "strict": true turns on a group of separate type-checking flags at once. You can then switch any single flag off by setting it explicitly. An explicit setting always wins over the umbrella, regardless of the order in the file.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}Strict mode changes only what the compiler reports. It does not change the JavaScript that is emitted, apart from alwaysStrict, which adds a "use strict" directive to output files. Turning it on makes more programs fail to compile, not behave differently at runtime.
The flags inside `strict`
The group below is for TypeScript 5.x. The TypeScript team can add new checks to strict in later releases, so upgrading the compiler can produce new errors in a project that compiled cleanly before.
| Flag | What it catches |
|---|---|
| `noImplicitAny` | Values whose type the compiler cannot infer and would silently treat as `any` |
| `strictNullChecks` | Using a value that might be `null` or `undefined` as if it were always present |
| `strictFunctionTypes` | Assigning a function whose parameter types are too narrow |
| `strictBindCallApply` | Wrong argument types passed to `bind`, `call`, and `apply` |
| `strictPropertyInitialization` | Class properties that are never assigned in the constructor |
| `noImplicitThis` | Using `this` where its type would be an implicit `any` |
| `useUnknownInCatchVariables` | Treating the variable in `catch (err)` as `any` instead of `unknown` |
| `alwaysStrict` | Emits `"use strict"` and parses files in JavaScript strict mode |
| `strictBuiltinIteratorReturn` | Iterator `return` values from built-ins that may be `undefined` (added in 5.6) |
The next sections cover the flags that produce most of the errors you will see.
`strictNullChecks`
Without this flag, null and undefined are assignable to every type, so the compiler lets you call methods on values that may not exist. With it on, null and undefined are separate types, and you must handle them before use.
function firstLetter(text: string | undefined): string {
return text.charAt(0);
}The compiler reports 'text' is possibly 'undefined'. Fix it by narrowing the type with a check:
function firstLetter(text: string | undefined): string {
if (text === undefined) {
return "";
}
return text.charAt(0);
}
console.log(firstLetter("hello"));
console.log(firstLetter(undefined));Inside the if block the compiler knows text is undefined. After the early return, it knows text is a string. This is called narrowing, and it is why strictNullChecks is usually considered the most valuable strict flag. A whole category of "cannot read properties of undefined" runtime errors becomes a compile-time error.
Other ways to satisfy the compiler are optional chaining (text?.charAt(0)) and the nullish coalescing operator (text ?? ""). The non-null assertion text! also silences the error, but it only tells the compiler to trust you. If you are wrong, the runtime error comes back.
`noImplicitAny`
When the compiler cannot infer a type and you have not written one, it falls back to any, which turns off checking for that value. noImplicitAny makes that fallback an error, so you must decide on a type.
function double(x) {
return x * 2;
}This reports Parameter 'x' implicitly has an 'any' type. Add an annotation:
function double(x: number): number {
return x * 2;
}
console.log(double(21));Writing x: any is still allowed. The flag does not forbid any. It forbids an accidental any. An explicit one is a visible decision that a reviewer can search for.
`strictPropertyInitialization`
This flag requires every class property to be assigned in the constructor, to have an initializer, or to include undefined in its type. It only has an effect when strictNullChecks is also on.
class User {
name: string;
nickname?: string;
constructor(name: string) {
this.name = name;
}
}If name were declared but never assigned, the compiler would report Property 'name' has no initializer and is not definitely assigned in the constructor. Optional properties like nickname are exempt because their type already includes undefined.
If a framework assigns the property after construction, you can use the definite assignment assertion, name!: string. Like ! on a value, this is a promise to the compiler that you must keep.
`useUnknownInCatchVariables`
In JavaScript anything can be thrown, not only Error objects. With this flag on, the variable in a catch clause has type unknown, so you must check it before reading properties.
function parse(json: string): unknown {
try {
return JSON.parse(json);
} catch (err) {
if (err instanceof Error) {
console.error(`Invalid JSON: ${err.message}`);
} else {
console.error("Invalid JSON: unknown failure");
}
return undefined;
}
}
console.log(parse("{bad"));Writing err.message directly would fail with 'err' is of type 'unknown'. This is a common surprise when you first enable strict mode on older code.
`strictFunctionTypes`
When one function type is assigned to another, parameter types must be compatible in the safe direction. A function that accepts only strings cannot stand in for a function that may be called with numbers.
type Handler = (event: string | number) => void;
const onlyStrings: Handler = (event: string) => {
console.log(event.toUpperCase());
};The compiler rejects the assignment because Handler could be called with 42, and toUpperCase does not exist on numbers. The check applies to function-typed properties and standalone function types. It does not apply to parameters of methods declared with method syntax, such as { handle(e: string): void }. The TypeScript team kept methods lenient so that common patterns, such as Array<T> being treated as covariant, keep working.
Adopting strict mode in an existing project
Turning on strict in a large JavaScript or loosely typed codebase can produce hundreds of errors at once. You have several options for spreading out the work.
- Enable flags one at a time. Start with
"strict": falseand turn on individual flags in order of effort. A common order isalwaysStrict,noImplicitThis,strictBindCallApply,useUnknownInCatchVariables,strictFunctionTypes,noImplicitAny, andstrictNullCheckslast, since the last two usually generate the most errors. - Enable
strictand opt out of the noisy flags. This keeps new checks on by default and lets you remove the exceptions one by one. - Use a second config for new code. A separate
tsconfig.strict.jsonthat extends the main file and includes only migrated directories lets you grow the strict area gradually.
Option 2 looks like this:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": false,
"strictNullChecks": false
}
}Option 3 uses extends:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strict": true,
"noEmit": true
},
"include": ["src/migrated"]
}Run the stricter check with npx tsc -p tsconfig.strict.json. Because it sets noEmit, it only reports errors and does not write files. Note that imports from unmigrated files still pull those files into the check, so errors in them can appear in the output.
Common mistakes
- Silencing errors with
anyor!everywhere. Each one removes a check, so a codebase full of them has the cost of strict mode and little of the benefit. Prefer narrowing, and search foranyand!during review. - Expecting
strictto change emitted code. It does not, except for the"use strict"directive. - Forgetting that
strictcan grow. After a compiler upgrade, new errors may appear. Pin the TypeScript version inpackage.jsonand read the release notes when you upgrade. - Putting
strictin the wrong place. It belongs insidecompilerOptions. At the top level of the file it is ignored. - Checking only the editor. The editor may use a different TypeScript version than your project. Run
npx tsc --noEmitin CI so the project's pinned compiler is the one that decides.
Exercise
A config sets "strict": true and "strictNullChecks": false. Is strictPropertyInitialization effectively active? Explain what you would expect to see for a class property id: number; that is never assigned.
Show answer
It is not effective. strictPropertyInitialization only has an effect when strictNullChecks is on, so the explicit false for strictNullChecks overrides the umbrella and the initialization check does nothing. The unassigned id: number; compiles without error. Depending on the compiler version, you may also get an error that strictPropertyInitialization requires strictNullChecks to be enabled.
Exercise
Rewrite this function so it compiles under strict: true without using any or !.
function lengthOf(items) {
return items ? items.length : 0;
}
Show answer
Annotate the parameter with a type that includes undefined, for example:
function lengthOf(items: string[] | undefined): number {
return items ? items.length : 0;
}
The annotation fixes the noImplicitAny error. The existing truthiness check narrows items to string[] before .length is read, which satisfies strictNullChecks.
Exercise
You enable strict and the compiler reports 'err' is of type 'unknown'. inside a catch (err) block that reads err.message. Which flag causes this, and what is the minimal fix?
Show answer
useUnknownInCatchVariables causes it. The minimal fix is to narrow the value before use, for example if (err instanceof Error) { console.error(err.message); }.