Run this yourself. Every flag below as a before/after pair, with the exact diagnostic code asserted:
typescript-strict-mode/in the Coding Dunia code-examples repo.
TypeScript strict mode is a single tsconfig.json setting that enables eight related compiler flags, catching null-reference bugs, implicit any types, and unsafe function assignments at compile time instead of letting them reach production as runtime crashes. If you're rolling strict mode out as part of a wider version bump, the TypeScript 7 migration guide covers the strict flags that changed behaviour in Corsa and what each one will newly flag in existing code.
On a new TypeScript project I turn on strict: true before the first commit. Not because it's fashionable, because it catches real bugs before they reach production. The repo I work in doesn't fully live up to that, and it's worth saying out loud: coding-dunia extends astro/tsconfigs/strict, but the shared library every blog imports still sets strict: false in its own tsconfig, and only one blog switches on noUncheckedIndexedAccess. That's where an old codebase drifts when nobody pays the entry fee.
Here's the thing most developers get wrong about TypeScript: a non-strict config gives you the syntax of static typing with almost none of the safety. You can write const name = obj.user.name and TypeScript won't blink, even if obj.user is nullable. That's not type safety. That's decoration. The same point runs through what TypeScript actually does, where a checker that never runs buys you syntax and nothing else.
TL;DR:
strict: trueintsconfig.jsonenables 8 compiler flags with one line (TypeScript Strict Mode Options)- The most impactful flag is
strictNullChecks, it forces you to handle null and undefined everywhere- Four extra flags beyond strict are worth adding:
noUncheckedIndexedAccess,exactOptionalPropertyTypes,noPropertyAccessFromIndexSignature, anduseUnknownInCatchVariables- Migrate existing codebases incrementally, flag by flag, using
// @ts-strict-ignoreto defer errors
Why Do Developers Skip Strict Mode?
The most common objection is "it causes too many errors." That's true. It's also the point.
When you enable strict: true on an existing codebase and see 500 errors, you haven't broken anything. You've made existing bugs visible. Every one of those errors represents a place where your code assumed something TypeScript can't prove. Most of them are legitimate bugs waiting for the wrong input.
Strict-mode migrations follow a pattern. The first flag that bites is strictNullChecks, and the errors cluster in places where undefined gets passed to a function expecting a string. Few of them will have unit tests. Some will sit in production code paths that have been silently returning wrong results for months.
A non-strict config gives you the syntax of static typing with almost none of the safety. That's not type safety. That's decoration.
The answer to "should I enable strict mode?" is almost always yes. The real question is only when and how fast.
Strict mode also surfaces the kind of nullable-access bugs that try/catch alone tends to paper over, the TypeScript code smells and anti-patterns guide walks through the production-error cases most developers hit first.
What Are the 8 Flags Inside strict Mode?
Setting strict: true in your tsconfig.json is shorthand for eight individual flags (TypeScript Strict Mode Options, 2024). Each flag targets a specific class of type error that TypeScript's permissive defaults would otherwise ignore.
| Flag | What it catches |
|---|---|
strictNullChecks | Prevents using null or undefined where a value is expected |
noImplicitAny | Errors on parameters and variables with inferred any type |
strictFunctionTypes | Enforces contravariant parameter types on function assignments |
strictBindCallApply | Type-checks arguments passed to .bind(), .call(), .apply() |
strictPropertyInitialization | Requires class properties to be initialized in the constructor |
noImplicitThis | Errors when this has an implicit any type |
useUnknownInCatchVariables | Types catch clause variables as unknown instead of any |
alwaysStrict | Emits "use strict" in every output file |
{
"compilerOptions": {
"strict": true
}
}
That one line expands to all eight. You can also enable them individually if you want finer control during migration (TypeScript Handbook - tsconfig Reference, 2024). Copying a config from the docs? Check it against your compiler first, because several Handbook examples fail on 7.0.2, as the TypeScript documentation map shows.
Setting strict: true in tsconfig.json is shorthand for eight individual compiler flags, according to the TypeScript Handbook. Each flag targets a different class of error, from null-reference bugs to implicit any types to unsafe this bindings.
What Are the Two Most Important Flags in Practice?
strictNullChecks
strictNullChecks is the flag that earns its keep. Without it, null and undefined are valid values for every type, a string variable can quietly be null, and TypeScript won't say a word.
A good small example is formData.get(), which returns a nullable value; form action errors under strict shows the two diagnostics it produces.
With it enabled, this code fails to compile:
function greet(name: string): string {
return "Hello, " + name.toUpperCase();
}
const user = getUser(); // returns User | null
greet(user.name); // Error: Object is possibly null
You're forced to handle the null case explicitly:
if (user !== null) {
greet(user.name); // TypeScript is now satisfied
}
This is where most runtime TypeError: Cannot read properties of null crashes get eliminated. The fix isn't always elegant, but the error is always honest.
noImplicitAny
noImplicitAny prevents TypeScript from silently widening an untyped parameter to any. Without it, this compiles without complaint:
function processData(data) {
return data.records.map((r) => r.id);
}
The parameter data is implicitly any. You get zero type checking on the entire function body. Enable noImplicitAny and TypeScript demands an annotation:
function processData(data: { records: { id: string }[] }) {
return data.records.map((r) => r.id);
}
It's more work upfront. It saves hours of debugging later.
If you're spending a lot of energy on optional / required combinations in narrow places, the TypeScript utility types guide covers Partial, Required, Pick, and the rest of the built-ins that make strict-mode code more readable instead of more verbose. For a fast lookup of the core type syntax those helpers build on, the TypeScript cheat sheet keeps the basics in one place.
What Flags Are Worth Adding Beyond strict Mode?
Four flags don't ship inside strict: true but are worth adding to every new project. On existing codebases, enable them after you've cleared all strict errors first.
If I could add only one of them, it would be noUncheckedIndexedAccess. That's an opinion, not a measurement: it forces you to answer "what if this index is empty?" at every array read, which is exactly the question off-by-one and empty-array bugs skip. It's oddly underrated.
noUncheckedIndexedAccess
This flag makes array indexing return T | undefined instead of T. That sounds annoying, and it is, at first.
const items = ["a", "b", "c"];
const first = items[0]; // type is string | undefined with this flag
first.toUpperCase(); // Error: Object is possibly undefined
Worth it. Arrays can be empty. You know this. Now TypeScript knows it too.
exactOptionalPropertyTypes
Without this flag, TypeScript treats { name?: string } as allowing { name: undefined }. With exactOptionalPropertyTypes enabled, setting an optional property to undefined explicitly is a type error. It sounds pedantic, but it catches real mismatches when you spread objects or map over optional fields.
noPropertyAccessFromIndexSignature
When your type has an index signature like [key: string]: string, this flag prevents dot-notation access (obj.knownKey) and requires bracket notation (obj["knownKey"]). It forces you to acknowledge that the property might not exist.
useUnknownInCatchVariables
Already included in strict: true in TypeScript 4.4+, but worth mentioning explicitly. Catch clause variables are typed as unknown instead of any. You can't call .message on an error without checking it first.
try {
riskyOperation();
} catch (err) {
// err is unknown, you must narrow it
if (err instanceof Error) {
console.error(err.message);
}
}
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noPropertyAccessFromIndexSignature": true
}
}
How Do You Migrate an Existing Codebase Incrementally?
You don't enable all flags at once. That's the rule. Here's the order that actually works:
- Enable
strictNullChecksonly, then fix every error. These are your highest-priority bugs, the ones that turn into production null-pointer crashes. - Enable
noImplicitAny. This generates the most noise on legacy code. Use// @ts-ignoreas a temporary escape hatch for things you can't fix immediately, but track them in a backlog. - Enable the remaining six strict flags together. At this point, most errors will be minor.
strictPropertyInitializationandstrictFunctionTypesare the most common sources of new complaints. - Add the four extra flags from the section above, one at a time, starting with
noUncheckedIndexedAccesssince it catches the most real bugs per flag.
For large codebases, the ts-migrate tool from Airbnb automates much of step 1 and 2. It converts implicit any parameters to explicit ones and adds // @ts-ignore comments where strict inference fails. You still need to review every change, but it cuts migration time dramatically.
Incremental adoption is the practice of turning on strict-mode flags one at a time, in priority order, instead of flipping strict: true all at once and facing thousands of unranked errors on day one. The // @ts-strict-ignore file-level comment is also useful: it disables strict checks for one file, letting you migrate module by module instead of fixing everything before you can even compile.
I don't have an hours-per-thousand-lines figure to give you, and I'd distrust anyone who does: the cost tracks how much of the code passes nullable values around, not how long the files are. What the repo I work in does instead is a ratchet. typecheck-projects.ts runs one tsc --noEmit -p per project, and the rule is no new errors rather than zero, which is how a non-strict project makes progress without a flag day.
Incremental adoption means enabling strict-mode flags one at a time instead of all eight at once, in priority order: strictNullChecks first, noImplicitAny second, then the rest, with a "no new errors" ratchet on every project that isn't clean yet.
What Does the Ladder Look Like on Legacy Code, Flag by Flag?
Two reader questions arrived within a day of each other, one asking for a case study of --strict on a real repository with before-and-after error counts, the other for the gotchas that bite on legacy code once strictNullChecks is on. They're the same question from two sides, so this is one section answering both. I don't have a public repository to hand you numbers for, and I'd rather say that than invent a tidy "412 errors became 0". What I can give you is a 60-line module that contains every pre-strict habit I keep meeting in 2019-era code, pushed through typescript 7.0.2 one flag at a time on 2026-10-09, with the counts the compiler printed. You can paste it and get the same table.
// legacy.ts: the shapes you meet in a codebase written before strict
type Order = { id: string; total: number; coupon?: string; shippedAt: Date | null };
const orders: Order[] = [];
const byId: { [id: string]: Order } = {};
export function findOrder(id) {
return orders.find((o) => o.id === id);
}
export function couponLength(order: Order) {
return order.coupon.length;
}
export function shippedYear(order: Order) {
return order.shippedAt.getFullYear();
}
export function firstOrderId() {
return orders[0].id;
}
export function lookup(id: string) {
return byId[id].total;
}
export function parseTotal(raw) {
return parseFloat(raw);
}
export class Cart {
items: Order[];
owner: string;
constructor(owner?: string) {
if (owner) { this.owner = owner; }
}
sum() {
return this.items.reduce((acc, o) => acc + o.total, 0);
}
}
export function onReady(cb: (err: Error) => void) {
cb(null);
}
export async function load(url: string) {
try {
const res = await fetch(url);
return await res.json();
} catch (e) {
console.log(e.message);
return null;
}
}
export function pick(list: string[], i: number) {
const v = list[i];
return v.toUpperCase();
}
The command for each row was tsc --noEmit --target es2022 --lib es2022,dom plus the flags in the first column. The baseline needs --strict false written out, and the reason is the first gotcha.
| Flags | Errors | Codes |
|---|---|---|
--strict false | 0 | |
--strict false --strictNullChecks | 3 | TS18048, TS18047, TS2345 |
--strict false --noImplicitAny | 2 | TS7006 x2 |
--strict false --strictNullChecks --noImplicitAny | 5 | the two rows above, added |
--strict | 8 | plus TS2564 x2, TS18046 |
--strict --noUncheckedIndexedAccess | 11 | plus TS2532 x2, TS18048 |
--strict --noUncheckedIndexedAccess --exactOptionalPropertyTypes | 11 | no change |
| no flags at all | 8 | same as --strict |
Gotcha one: no flags means strict on TypeScript 7. The last row is the one that surprised me. Run tsc legacy.ts with no config and 7.0.2 reports all eight strict errors, because strict is the default in the Go compiler. A migration ladder on TS 7 has to start from an explicit "strict": false in tsconfig.json, or the baseline you measure against is already the destination. Older codebases that upgraded the compiler before planning the migration will have met this as a surprise wall of errors on day one.
Gotcha two: three different findings from one flag. Only one of the strictNullChecks errors is a null check. TS18048 on order.coupon.length is an optional property read without a guard. TS18047 on order.shippedAt.getFullYear() is a declared Date | null read without a guard. And TS2345 on cb(null) is the one teams miss when they estimate the work: a callback typed (err: Error) => void was always called with null on the success path, Node style, and the type was a lie the whole time. The fix is to change the signature to (err: Error | null) => void, which then ripples into every caller that read err.message without checking. Type guards are the tool for the first two:
export function couponLength(order: Order) {
return order.coupon?.length ?? 0;
}
export function shippedYear(order: Order) {
if (order.shippedAt === null) {
return undefined;
}
return order.shippedAt.getFullYear();
}
The ?? 0 is a decision, not a translation. Before strict, couponLength on an order without a coupon threw TypeError at runtime; after, you have to say what the answer is. That's the part of a strict migration that costs thinking rather than typing, and no codemod does it for you.
Gotcha three: class errors hide until the umbrella flag. TS2564, "Property 'items' has no initializer and is not definitely assigned in the constructor", comes from strictPropertyInitialization, which has no effect without strictNullChecks and in practice arrives when you flip the umbrella flag. Cart.items was never assigned anywhere. sum() would have thrown on the first call. The owner case is subtler: it's assigned inside an if, so the compiler is right that it might not be. Either make it owner?: string and handle that downstream, or initialise it to '' and accept a sentinel.
Gotcha four: the index flag keeps paying. Going from --strict to adding it took the count from 8 to 11, and all three additions are real: orders[0].id on a possibly-empty array, byId[id].total on a map that may not contain the key, and list[i] in pick. The first two surface as TS2532, "Object is possibly 'undefined'", the third as TS18048 with the variable name. In a legacy codebase this flag produces the most errors per line of config, which is exactly why it's worth turning on last and fixing deliberately rather than with !.
Gotcha five: a flag that finds nothing is informative. exactOptionalPropertyTypes added no errors because the sample never assigns undefined to an optional property explicitly, so the flag has nothing to say. On a codebase that spreads partial objects around, it will. A flag that adds zero errors is cheap to turn on now and expensive to turn on later, after the habit forms.
Every error a strict flag adds to legacy code was already a runtime failure waiting for the right input; the flag didn't create the bug, it moved the discovery from a user to a terminal.
What I won't claim is how long any of this takes on a codebase a hundred times bigger. Eleven errors in sixty lines is the density of code written to trigger them; your ratio will be lower, and the three strictNullChecks kinds will dominate it. The order to do it in is the one the section above lays out, and the sample is the thing to check that order against before you commit a team to it.
Does Strict Mode Make AI Coding Tools Better?
Yes, significantly. This is one of the less obvious benefits.
AI code assistants like GitHub Copilot and Cursor read your type signatures to generate suggestions. When your codebase has explicit types everywhere, enforced by strict mode, the AI has more signal to work with. You'll get completions that correctly handle nullable fields. You'll see function suggestions that match your actual parameter types.
Without strict mode, the AI sees any everywhere and has to guess. With strict mode, it sees your actual domain model. The suggestions tend to be more accurate. I haven't benchmarked that, so treat it as a mechanism rather than a measurement: tighter types mean better AI outputs, not just safer runtime behavior.
For the TypeScript-specific workflows where strict types change what AI tools like Cursor and GitHub Copilot can generate, Cursor AI TypeScript productivity tips covers 20 patterns, including how discriminated unions become the most reliable prompts you can give an AI model.
Strict mode isn't a style preference. It's the foundation that makes TypeScript actually work as advertised, for you and for every tool that reads your code. TypeScript 5.8 and TypeScript 7 (Corsa), which reached GA in July 2026, both assume you're using it. The complete 2026 picture is clear: non-strict TypeScript is a liability, and the migration cost is always lower than the cost of the bugs you'll ship without it.
What Should You Read Next?
- TypeScript AI agents
- TypeScript form validation
- SOLID in TypeScript
- TypeScript 7 Migration: What Changed and How to Upgrade