iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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-flagCatches
noImplicitAnyA value TS couldn't infer falls to any — error instead.
strictNullChecksnull / undefined are no longer assignable to T.
strictFunctionTypesFunction-type parameter variance is checked correctly.
strictBindCallApplybind/call/apply are typed.
strictPropertyInitializationClass field has no initializer or constructor assignment.
noImplicitThisthis typed as any in a free function.
alwaysStrictEmit 'use strict' at the top of every file.
useUnknownInCatchVariablescatch (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:

  1. Add "strict": true to a new sub-tsconfig used only by new code.
  2. Migrate files one at a time — TS shows you what to fix.
  3. Optional: install ts-strict-migrate to track per-file progress.
  4. 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

Test yourself

Q1. "strict": true enables several checks at once. Which is NOT one?
Q2. For green-field projects you should set strict…
Q3. In strict mode, catch (e) gives e the type…

Discussion

Loading…