Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readTypeScript
#TypeScript#Migration#Type Safety#tsconfig
3D illustration of a type checker gate turning loosely typed blocks into narrow typed blocks

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:

json
{ "compilerOptions": { "target": "ES2022", "module": "nodenext", "strict": true, "noUncheckedIndexedAccess": true, "noEmit": true }, "include": ["src"] }
ts
// 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: unknown

npx 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:

bash
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 code

Errors 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 strictWhat it forbidsTypical error
strictNullChecksAssigning null/undefined to a non-nullable typeTS2322, TS18047, TS2531
noImplicitAnyUnannotated parameters and untyped valuesTS7006, TS7031, TS7053
strictFunctionTypesUnsound parameter bivariance in callbacksTS2322, TS2345
strictBindCallApplyLoose bind/call/apply argumentsTS2345
strictPropertyInitializationUninitialized class fieldsTS2564
useUnknownInCatchVariablescatch (e) typed as anyTS18046
noUncheckedIndexedAccess (not in strict)Assuming an index existsTS18048
FixSoundCostUse when
if (x) / ??YesNoneDefault
Type guard function (x is T)YesOne functionReused checks
Discriminated union + switchYesRestructureMultiple optional states
unknown + validationYesA parser (zod, valibot)External data
Non-null assertion !NoHides the nullOnly when a check exists elsewhere
as TNoHides everythingNever for nullability

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. DOM queries: getElementById returns T | null

ts
// 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

ts
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]; // string

noUncheckedIndexedAccess 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

ts
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

ts
// 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

ts
// 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

json
{ "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

MistakeSymptomCorrect approach
Sprinkling ! until it compilesBuilds, crashes in productionNarrow, or throw with a message
as unknown as T to bypass a nullSame crash, less informationModel the nullable state
Enabling strict in a 500-file PRReview paralysis, revertPer-directory tsconfig or one flag at a time
// @ts-ignoreHides the next error on that line too// @ts-expect-error fails when obsolete
catch (e: any) everywhereKeeps unsound accessunknown plus instanceof
noUncheckedIndexedAccess on day oneHundreds of new errors on top of strictSecond pass
strictPropertyInitialization with decoratorsConstructor 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 tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.