Strict Mode
"Strict mode" is the recommended TypeScript baseline. "strict": true in tsconfig flips on several smaller checks at once.
What it turns on
| Sub-flag | Catches |
|---|---|
noImplicitAny | A value TS couldn't infer falls to any — error instead. |
strictNullChecks | null / undefined are no longer assignable to T. |
strictFunctionTypes | Function-type parameter variance is checked correctly. |
strictBindCallApply | bind/call/apply are typed. |
strictPropertyInitialization | Class field has no initializer or constructor assignment. |
noImplicitThis | this typed as any in a free function. |
alwaysStrict | Emit 'use strict' at the top of every file. |
useUnknownInCatchVariables | catch (e) — e is unknown, not any. |
Bonus flags worth adding
tsconfig.json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noPropertyAccessFromIndexSignature": true
}
}
Why bother
- Most "TypeScript didn't help me here!" stories trace back to flags that should have been on.
- The compile-time cost of strict mode is small; the runtime cost of missing these bugs is large.
- Code review can focus on logic, not "is this null when it shouldn't be?".
Adopting strict in an existing project
Don't try to turn everything on at once. Phase it:
- Add
"strict": trueto a new sub-tsconfig used only by new code. - Migrate files one at a time — TS shows you what to fix.
- Optional: install
ts-strict-migrateto track per-file progress. - Once everything passes, flip the root tsconfig.
Tip: If you control a green-field project, set
strict: true + noUncheckedIndexedAccess: true on day one. Future-you will be smug.Example
Example
// In strict mode, these become errors:
// - implicit any
// - null / undefined slipping through
// - this in a function not bound
// - returning undefined from a non-void function
//
// Turn it on: "strict": true in tsconfig.json.
console.log('Strict mode is the recommended default');
Try it Yourself »
Exercise
Master flag that enables every strict check.
"
": true
Six letters.
Discussion
Loading…