Explain it simply
Strict mode in plain words
tsconfig.json is the settings file that tells the compiler how strictly to check your code. With the checks turned off the compiler is friendly, but it lets most bugs through. The single line `"strict": true` switches on the most important checks at once.
One thing to remember: however strict the settings, the compiler only checks your source code. It never sees the data that arrives from an API while the program runs, because by then the types have been erased.
Problem → Why → Solution
The problem: it compiles, then it crashes
With the checks off, the code below compiles without a single error. TypeScript treats `words[0]` as a `string` and never asks whether the array has any elements. Call it with an empty array and `first` is `undefined`, so `first.length` crashes with a TypeError.
In `double`, the parameter has no type, so `x` quietly becomes `any`. Calling `double("5")` raises no complaint and returns `10`, correct only because JavaScript happened to convert the string.
function firstWordLength(words: string[]) {
const first = words[0]; // typed as string, but [] gives undefined
return first.length; // TypeError: Cannot read properties of undefined
}
function double(x) { // x is silently 'any'
return x * 2;
}
firstWordLength([]);What the strict settings change
`strict` rejects `double(x)` with 'Parameter x implicitly has an any type'. `noUncheckedIndexedAccess` changes the type of `words[0]` to `string | undefined`, so `first.length` reports 'first is possibly undefined'. Both crashes become compile errors before anything runs.
Core concept: the strict family and the compiler's boundary
`"strict": true` is not one option but a master switch for a family of checks. When a new TypeScript version adds another strict check, it usually lands under this switch too. So rather than listing checks one by one, turn `strict` on and switch off an individual check only if you truly must. The most important members are:
| Check | What it catches |
|---|---|
| noImplicitAny | Parameters that silently become any |
| strictNullChecks | Using a value that may be null or undefined |
| strictPropertyInitialization | Class properties never set in the constructor |
| useUnknownInCatchVariables | Makes err in catch (err) unknown instead of any |
Two more checks are not part of `strict`, and they are worth enabling too. `noUncheckedIndexedAccess` adds `| undefined` to every value read through `array[i]` or `object[key]`, forcing you to handle a missing index. `exactOptionalPropertyTypes` makes `nickname?: string` mean only 'the key may be absent', and rejects writing `nickname: undefined` explicitly.
The compiler boundary is where tsc's responsibility ends. tsc checks your source and, unless `noEmit` is set, writes JavaScript. No setting can check data that arrives at run time from `JSON.parse` or `fetch`; that has to be validated by code. In projects where a bundler or `tsx` produces the JavaScript, `noEmit: true` turns tsc into a pure type checker.
The remaining options are not checks; they describe the environment the code will run in. `target` chooses which JavaScript version to emit (for example `es2022`), while `module` and `moduleResolution` decide how `import` statements are written and how files are found. Getting these wrong does not produce type errors but problems like 'Cannot find module' or imports that break at run time. So the check settings can be identical across projects, while the environment settings depend on where each project runs.
- strict: switch on the family
- Extra flags: indexes, optionals
- tsc checks source code only
- Runtime data: validate in code
tsconfig decides how strictly your code is checked; it never checks data from outside.
General pattern: tsconfig.json
{
"compilerOptions": {
"strict": true,
"<extraCheck>": true,
"target": "<JS version to emit>",
"module": "<module system>"
},
"include": ["<source glob>"]
}`compilerOptions` holds the checks and output settings; `include` says which files are checked. Although it looks like JSON, tsconfig.json allows comments and trailing commas.
A strict tsconfig
This tsconfig is for a project where a bundler (Vite, for example) produces the JavaScript, so tsc only type-checks and writes no files. It sets `"target": "es2022"`, a year target that every TypeScript 5.x release accepts and that current browsers and Node versions support. Year targets only go as high as your compiler knows: TypeScript 5.x stops at `es2024`, so a value such as `es2025` is rejected.
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"target": "es2022",
"module": "esnext",
"moduleResolution": "bundler",
"isolatedModules": true,
"noEmit": true
},
"include": ["src/**/*.ts"]
}Code breakdown
- The strict family
"strict": true,Switches on the whole family, including noImplicitAny and strictNullChecks. This line is what catches `double(x)` from the problem.
- Safer indexing
"noUncheckedIndexedAccess": true,Makes `words[0]` a `string | undefined`, turning the empty-array crash into a compile error.
- Exact optional properties
"exactOptionalPropertyTypes": true,Distinguishes 'key missing' from 'key present with undefined' for optional properties, and rejects `{ nickname: undefined }`.
- How code is resolved and emitted
"moduleResolution": "bundler",Resolves imports the way a bundler does. For code that Node.js runs directly, use `"module": "nodenext"` instead. These settings must match the environment the code will actually run in.
- Type-check only
"noEmit": truetsc writes no `.js` files because the bundler does that. `isolatedModules` complements it by guaranteeing each file can be turned into JavaScript on its own, without type information.
Rewriting the code for the strict tsconfig
Instead of silencing strict errors with `!` or `as`, handle the case the compiler is warning you about. The code below rewrites the function from the problem to check for `undefined`, and creates an optional property by leaving the key out. It compiles cleanly under this lesson's tsconfig.
// Compiles under the strict tsconfig from this lesson.
function firstWordLength(words: string[]): number {
const first = words[0]; // string | undefined
return first === undefined ? 0 : first.length;
}
type Profile = { name: string; nickname?: string };
const su: Profile = { name: "Su" }; // leave the key out instead of nickname: undefined
console.log(firstWordLength(["strict", "mode"]));
console.log(firstWordLength([]));
console.log(su.nickname ?? "(no nickname)");This prints `6`, `0` and `(no nickname)`. After the `first === undefined` check, TypeScript narrows `first` to `string`, so `first.length` is allowed. Whether an empty array should give 0 or throw an error is a business decision; what matters is that the case is now a deliberate choice instead of an accident.
In real projects
Strict mode in real projects
For a new project, starting with `strict: true` on day one is easiest: there is little code yet, so there are few errors. When converting an existing JavaScript project, teams usually enable checks one at a time: `noImplicitAny` first, then `strictNullChecks`, then full `strict`, fixing each batch of errors before turning on the next.
In monorepos, a single base tsconfig holds the shared settings and every package inherits it with `"extends": "../../tsconfig.base.json"`, so strictness cannot drift between packages. Running `tsc --noEmit` in CI, plus runtime validation with a library such as zod at API boundaries, covers both compile time and run time. Code reviewers also learn to treat a new `!` or `as` in a pull request as a question worth asking.
Common mistakes
Common tsconfig mistakes
Turning strict off because errors appeared
Switching on `strict: true` and seeing hundreds of errors makes you want to set it back to `false`. But each of those errors is a possible crash. Turning strict off, or sprinkling `value!` (the non-null assertion) everywhere, only hides the bugs. Enable the checks one at a time and fix them gradually.
Copying an option value your compiler does not know
Suppose a tsconfig you copied contains `"target": "es2025"`. With TypeScript 5.x, `npx tsc` stops immediately with 'Argument for --target option must be ...' (TS6046), before checking a single file. When copying a tsconfig from a blog post, check the official docs for whether each value exists in your project's TypeScript version.
Setting `noEmit` and then looking for `dist/`
With `noEmit: true`, tsc writes no files at all. For a project that Node.js runs directly, remove `noEmit` and set `outDir` instead.
Best practices
Good tsconfig habits
- Start every new project with `strict`, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` on
- Add a one-line comment explaining each option you add (tsconfig.json allows comments)
- In a repo with many packages, share one base tsconfig through `extends`
Mini challenge
Mini challenge: strict-safe lookups
Write two functions that compile cleanly under this lesson's tsconfig, without using `!` or `as`.
- `priceOf(item: string): string` returns the price with two decimals, or `not on the menu`
- `firstAndLast(items: string[]): string` returns `first ... last`, or `(empty list)` for an empty array
- Handle the possible `undefined` that `noUncheckedIndexedAccess` adds to every indexed read
// Record<string, number>: an object with string keys and number values
const prices: Record<string, number> = { tea: 1.5, coffee: 2.25 };
function priceOf(item: string): string {
// TODO: read prices[item] - its type is number | undefined here
// TODO: return "<item>: <price, 2 decimals>" or "<item>: not on the menu"
}
function firstAndLast(items: string[]): string {
// TODO: items[0] and the last item may both be undefined
}
// TODO: print priceOf("tea"), priceOf("juice"), and firstAndLast for a list and []Expected: Prints `tea: 1.50`, `juice: not on the menu`, `setup ... types` and `(empty list)`, and `npx tsc` reports no errors.
Show hint
Store the value in a variable first, then check `if (value === undefined) return ...`. Below that line TypeScript narrows it to `number` (or `string`).
Show solution
const prices: Record<string, number> = { tea: 1.5, coffee: 2.25 };
function priceOf(item: string): string {
const price = prices[item]; // number | undefined
if (price === undefined) return `${item}: not on the menu`;
return `${item}: ${price.toFixed(2)}`;
}
function firstAndLast(items: string[]): string {
const first = items[0];
const last = items[items.length - 1];
if (first === undefined || last === undefined) return "(empty list)";
return `${first} ... ${last}`;
}
console.log(priceOf("tea"));
console.log(priceOf("juice"));
console.log(firstAndLast(["setup", "strict", "types"]));
console.log(firstAndLast([]));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- `strict: true` is a master switch for checks such as noImplicitAny and strictNullChecks
- `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` must be enabled separately
- Handle the `undefined` case instead of hiding strict errors with `!` or `as`
- `target`, `module` and `moduleResolution` must match your runtime and your compiler version
- tsc only checks source code; runtime data must be validated in code
TypeScript Compiler Options — TypeScript