TypeScript strict Mode: TS2531, TS7006, and TS18047 Migrations
strict is nine flags at once. Count errors per code, fix them in the order that keeps the build green, and narrow instead of asserting.

Introduction & Quick Summary
Symptom. Turning on "strict": true produces a wall of errors in a project that compiled a minute earlier: error TS2531: Object is possibly 'null', error TS18047: 'user' is possibly 'null', error TS18048: 'items.length' is possibly 'undefined', error TS7006: Parameter 'e' implicitly has an 'any' type, error TS7031: Binding element 'id' implicitly has an 'any' type, plus TS2322/TS2345 assignability errors that appeared only because a null is now part of a type.
Cause. strict is not one check. It is a bundle of flags: noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, alwaysStrict, and (since TypeScript 4.4) useUnknownInCatchVariables. Enabling it changes the type of almost every value that can be absent, and turns every untyped parameter into an error. The errors are correct; the code was always doing this, it just was not verified.
Fix. Adopt in an order that keeps the build green: strictNullChecks and noImplicitAny first or together, then strictFunctionTypes and useUnknownInCatchVariables, then strictPropertyInitialization once class fields are initialized. Fix the errors with narrowing (if, in, typeof), ?? and ?., discriminant unions, and unknown at the catch boundary — not with ! everywhere, which silences the error and keeps the crash.
Core Mechanics, Signatures & Reproducible Setup
Under strictNullChecks, null and undefined are no longer assignable to every type, so string | null and string are different types and every member access on the union must be narrowed first. Under noImplicitAny, a parameter with no annotation and no contextual type becomes an error instead of any. strictPropertyInitialization requires every class property to be assigned in the constructor or declared with a definite assignment assertion.
Reproduce the whole set in one file with a minimal config:
{
"compilerOptions": {
"target": "ES2022",
"module": "nodenext",
"strict": true,
"noUncheckedIndexedAccess": true,
"noEmit": true
},
"include": ["src"]
}// src/demo.ts
export function initials(user: { name?: string | null }) {
return user.name!.split(' ').map((p) => p[0]).join(''); // TS2531 / TS18047
}
export function handle(e) { // TS7006
return e.target.value;
}
export const rows = ['a', 'b'];
export const first = rows[0].toUpperCase(); // with noUncheckedIndexedAccess
export class Store {
cache: Map<string, string>; // TS2564
save(k: string, v: string) { this.cache.set(k, v); }
}
try { JSON.parse('') } catch (err) { console.log(err.message); } // TS18046: unknownnpx tsc --noEmit reports every one. Each error maps to a specific narrowing technique, and running the compiler is the fastest way to see the shape of the problem in your own codebase:
npx tsc --noEmit | cut -d'(' -f1 | sort | uniq -c | sort -rn | head -15 # errors per file
npx tsc --noEmit | grep -o 'TS[0-9]*' | sort | uniq -c | sort -rn # errors per codeErrors per code tell you which flag is doing most of the work; errors per file tell you where to start.
Key Comparison Table
Flag inside strict | What it forbids | Typical error |
|---|---|---|
strictNullChecks | Assigning null/undefined to a non-nullable type | TS2322, TS18047, TS2531 |
noImplicitAny | Unannotated parameters and untyped values | TS7006, TS7031, TS7053 |
strictFunctionTypes | Unsound parameter bivariance in callbacks | TS2322, TS2345 |
strictBindCallApply | Loose bind/call/apply arguments | TS2345 |
strictPropertyInitialization | Uninitialized class fields | TS2564 |
useUnknownInCatchVariables | catch (e) typed as any | TS18046 |
noUncheckedIndexedAccess (not in strict) | Assuming an index exists | TS18048 |
| Fix | Sound | Cost | Use when |
|---|---|---|---|
if (x) / ?? | Yes | None | Default |
Type guard function (x is T) | Yes | One function | Reused checks |
Discriminated union + switch | Yes | Restructure | Multiple optional states |
unknown + validation | Yes | A parser (zod, valibot) | External data |
Non-null assertion ! | No | Hides the null | Only when a check exists elsewhere |
as T | No | Hides everything | Never for nullability |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. DOM queries: getElementById returns T | null
// Broken under strict
const canvas = document.getElementById('chart');
const ctx = canvas.getContext('2d');
// Fixed: fail loudly at the boundary
const canvas = document.getElementById('chart');
if (!(canvas instanceof HTMLCanvasElement)) throw new Error('#chart missing');
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('2d context unavailable');as HTMLCanvasElement is the shortcut most migrations take, and it is exactly the cast that keeps a null crash alive. Narrow with instanceof, then throw with a message that names the element.
2. Array access and noUncheckedIndexedAccess
const parts = path.split('/');
const last = parts[parts.length - 1]; // string | undefined once the flag is on
// Fixed
const last = parts.at(-1) ?? '';
// or prove the length first
if (parts.length === 0) throw new Error('empty path');
const last = parts[parts.length - 1]; // stringnoUncheckedIndexedAccess is not part of strict and is worth enabling in a second pass: it is the flag that catches the off-by-one that strict alone lets through. Enable it after the strict migration is green, not during.
3. Class properties that are set later
class Repo {
private client: Client; // TS2564
constructor(private token: string) {
this.client = new Client(token); // assigned in constructor — fine
}
}
class Lazy {
private client?: Client; // honest: maybe not yet
get(): Client {
return (this.client ??= new Client());
}
}Use ? when the field is genuinely optional, assign in the constructor when it is required, and reserve client!: Client for the framework-managed case (dependency injection, decorators) where assignment provably happens before first use.
4. catch variables are unknown
// Broken
try { await save() } catch (e) { if (e.status === 409) retry(); } // TS18046
// Fixed
try {
await save();
} catch (e) {
if (e instanceof HttpError && e.status === 409) retry();
else throw e; // never swallow
}For non-Error throws (a library that throws a string), instanceof fails and the error is rethrown — which is better than reading a property off unknown. If you need the old behaviour for one file, catch (e: any) is legal and explicit; the flag only removes the implicit any.
5. Callback parameter variance
// Broken under strictFunctionTypes: a handler that accepts fewer shapes
declare function on(event: string, cb: (e: MouseEvent | KeyboardEvent) => void): void;
on('x', (e: MouseEvent) => {}); // TS2345
// Fixed: accept the union, then narrow
on('x', (e) => {
if (e instanceof MouseEvent) { /* … */ }
});This error appears mostly in wrapper libraries whose callback type is narrower than the DOM's. Widening the wrapper's signature ((e: MouseEvent) => void → (e: Event) => void) usually fixes a dozen call sites at once.
6. Third-party types and skipLibCheck
{
"compilerOptions": {
"strict": true,
"skipLibCheck": true
}
}skipLibCheck skips type checking of .d.ts files, which is the pragmatic answer when a dependency ships declarations that fail under strict. It does not weaken your own code. The related trap: two packages pin different versions of @types/node, and errors appear in node_modules paths only after strict, because the declarations were never checked before. Align versions with npm ls @types/node before adding suppressions.
Common Compilation/Runtime Mistakes & Version Gotchas
| Mistake | Symptom | Correct approach |
|---|---|---|
Sprinkling ! until it compiles | Builds, crashes in production | Narrow, or throw with a message |
as unknown as T to bypass a null | Same crash, less information | Model the nullable state |
Enabling strict in a 500-file PR | Review paralysis, revert | Per-directory tsconfig or one flag at a time |
// @ts-ignore | Hides the next error on that line too | // @ts-expect-error fails when obsolete |
catch (e: any) everywhere | Keeps unsound access | unknown plus instanceof |
noUncheckedIndexedAccess on day one | Hundreds of new errors on top of strict | Second pass |
strictPropertyInitialization with decorators | Constructor never assigns | ! or a factory |
Version notes: TypeScript 5.x changed how strict interacts with moduleResolution: bundler and how verbatimModuleSyntax handles type-only imports, so a migration that also bumps the compiler can produce TS1484 ('X' is a type and must be imported using a type-only import) alongside the strict errors — fix those first, because they are mechanical. TypeScript 5.5 added inferred type predicates, which silently removes a class of errors that previously needed an explicit x is T guard; if a guard disappears during the migration, confirm the inference before deleting the annotation. With exactOptionalPropertyTypes (not in strict) also enabled, { a?: string } no longer accepts { a: undefined }, which is a separate, larger migration.
For the surrounding work, the JSON formatter is useful for reading the tsconfig chain output of tsc --showConfig, the text diff tool compares a file before and after tsc --noEmit --pretty false when the error count looks wrong, and the regex tool builds the pattern that turns an error dump into a per-code summary when grep is not enough.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript Generic Parameter Defaults: Syntax, Precedence, and Inference
When a default applies and when inference wins, defaults that reference earlier parameters, and how a defaulted type parameter keeps a library change non-breaking.
TypeScript Branded Types: Nominal Typing, Type Tags, and Validation
How a phantom property makes two strings incompatible, unique symbol brands, unit-typed numbers, and the places where a brand quietly disappears.
TypeScript Ambient Declarations: .d.ts Files, declare, and declare global
How declare and .d.ts files describe runtime values, wildcard modules for assets, declare global with var, and module augmentation of third-party types.
TypeScript Discriminated Unions: Exhaustiveness Checking and the never Type
Why the discriminant must be a literal, how never closes an exhaustive switch, and the duplicate-discriminant bug that lets a missing case compile.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.