Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 96 ยท Getting Started

Strict Mode Explained

Learn every flag behind TypeScript's strict option - strictNullChecks, noImplicitAny, strictFunctionTypes and more - each shown with the real bug it prevents.

"strict": true in tsconfig.json doesn't switch on one check. It switches on a whole family of checks, each one closing a specific gap where plain JavaScript habits would let a bug through. Without strict, TypeScript is deliberately forgiving so that old JavaScript projects can adopt it gradually. With strict, it behaves like the language most people mean when they say "TypeScript".

In this lesson you'll meet every flag in the family, see the bug each one catches, and learn the usual fix. You'll also look at two popular extra options that aren't part of strict: noUncheckedIndexedAccess and exactOptionalPropertyTypes. All of our editors run in strict mode, so every error shown here is exactly what the editors report.

The strict family

Setting strict to true turns on these options. You can still turn an individual one off, for example "strictPropertyInitialization": false, but new projects should keep them all.

Flag What it catches
strictNullChecks Using a value that might be null or undefined
noImplicitAny Values whose type silently becomes any
strictFunctionTypes Callbacks that accept less than the caller will pass
strictBindCallApply Wrong arguments to call, apply and bind
strictPropertyInitialization Class fields that are never assigned
useUnknownInCatchVariables Treating a caught error as if it were always an Error
noImplicitThis this with an unknown type
alwaysStrict Code that doesn't run in JavaScript's own strict mode
strictBuiltinIteratorReturn Ignoring the "done" result of built-in iterators

Newer TypeScript versions occasionally add a flag to this family (strictBuiltinIteratorReturn arrived in 5.6), so upgrading can reveal new errors. That's by design: strict always means "the strictest standard settings of this version".

TypeScript strict mode is not JavaScript strict mode. JavaScript's 'use strict' changes how code runs. TypeScript's strict changes how code is checked. They're connected only through alwaysStrict, described below. The JavaScript side is covered in the JavaScript course's Strict Mode lesson.

strictNullChecks

This is the most important flag of all. Without it, null and undefined are allowed in every type: a string variable might secretly hold null, and the compiler never warns you. With it, null and undefined are separate types, and a value that might be one of them must be checked before use.

The everyday source of undefined is a search that finds nothing:

TypeScript A search that may find nothing (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler reports main.ts(7,13): error TS18048: 'user' is possibly 'undefined'. find returns the type { id: number; name: string } | undefined, because there may be no match. Without the flag, this code compiles and crashes with a TypeError when the user doesn't exist. The fix is to handle the missing case:

TypeScript Handling the missing case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints Ada, (unknown user) and nobody. After the if, TypeScript knows user can no longer be undefined; this is called narrowing, and it gets a whole lesson in Narrowing. The last line shows the short form: optional chaining ?. stops at undefined, and ?? supplies a fallback (see Nullish Coalescing and Optional Chaining).

You'll see two variants of the error message: TS18048: 'user' is possibly 'undefined'. when the value has a name, and TS2532: Object is possibly 'undefined'. for an unnamed expression such as users.find(...).name. TS18047 is the same for null.

noImplicitAny

When TypeScript can't figure out a type and you haven't written one, it falls back to any, a type that allows everything and checks nothing. noImplicitAny turns that silent fallback into an error. The usual trigger is a parameter without an annotation:

TypeScript An untyped parameter (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error is main.ts(1,22): error TS7006: Parameter 'amount' implicitly has an 'any' type. Without the flag, amount would be any, both calls would compile, and the second would crash at runtime because strings have no toFixed. Adding amount: number fixes the function and turns the bad call into a proper error at the call site. Explicitly written any is still allowed, which is why any, unknown, never and void teaches you to avoid it.

strictFunctionTypes

This flag checks function types contravariantly in their parameters. The idea is simpler than the name: a function you hand over must be able to accept everything the caller might give it.

TypeScript A callback that accepts too little (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler rejects the assignment:

TEXT
main.ts(5,7): error TS2322: Type '(value: string) => void' is not assignable to type 'Handler'.
  Types of parameters 'value' and 'value' are incompatible.
    Type 'string | number' is not assignable to type 'string'.
      Type 'number' is not assignable to type 'string'.

A Handler may be called with a number, but shout only knows how to handle strings. Without the flag, the assignment compiles and handle(42) crashes with value.toUpperCase is not a function. The fix is a function that handles the full parameter type:

TypeScript
const shout: Handler = (value) => console.log(String(value).toUpperCase());

There's one deliberate exception: parameters of methods declared with method syntax (m(value: string): void inside an interface) are still checked the old, looser way, for compatibility with common library patterns. Declare callback members as properties (m: (value: string) => void) to get full checking. Type Compatibility and Variance explains the theory.

strictBindCallApply

call, apply and bind invoke a function indirectly. Without this flag, their arguments aren't checked at all. With it, they're checked exactly like a normal call:

TypeScript Checked call, apply and bind

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints Hello, Ada!, Hi, Lin!, Welcome, Sam! and finally Hey, 42!. That last call is wrong on purpose. The // @ts-expect-error comment tells the compiler "I know the next line has a type error", so the program still runs. If the line didn't have an error, the comment itself would become an error, so it can't hide anything by accident. Delete the comment and you get TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. This course uses @ts-expect-error now and then to show an error inside an otherwise runnable example. In real code, prefer fixing the error.

strictPropertyInitialization

In a class, a field declared with a type must be assigned, either where it's declared or in the constructor. Otherwise it's undefined at runtime even though its type says otherwise:

TypeScript A field nobody assigns (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error is main.ts(3,3): error TS2564: Property 'balance' has no initializer and is not definitely assigned in the constructor. The fixes are to give it a value (balance = 0; or balance: number = 0;), assign it in the constructor, or make the type honest (balance?: number or balance: number | undefined). For the rare field that's assigned somewhere TypeScript can't see, like by a framework, there's the definite-assignment assertion balance!: number. Classes covers all four. This flag only works together with strictNullChecks.

useUnknownInCatchVariables

Anything can be thrown in JavaScript: an Error, a string, a number, even undefined. So the variable in a catch clause has the type unknown, which forces you to check what you actually caught:

TypeScript Caught values are unknown (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler says main.ts(8,26): error TS18046: 'error' is of type 'unknown'. Without the flag, error would be any, and error.message would be undefined if some code threw a plain string. The fix checks before using it:

TypeScript Narrowing a caught error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first line starts with SyntaxError: followed by the JSON parser's message, and the second is Non-error value thrown: just a string. Error Handling builds on this pattern.

noImplicitThis

A regular function gets its this from the way it's called. If TypeScript can't tell what this is, it would be any. This flag makes that an error:

TypeScript this with an unknown type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

You get two errors, the first being main.ts(2,13): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. The fix is a special first parameter named this that declares its type; it's erased from the output and doesn't count as a real parameter:

TypeScript Declaring the type of this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints Ada is 36. Calling describe() on its own would now be an error, because there's no Person to be this. More often you'll use classes or arrow functions, where this is known automatically; see this, Parameter Destructuring and Type Predicates.

alwaysStrict

This flag makes TypeScript parse every file in JavaScript's strict mode and emit 'use strict'; at the top of files that aren't ES modules. ES modules are always strict anyway, so in a modern project with import/export it changes nothing visible. It still matters for scripts and CommonJS output: it forbids with statements, octal literals like 012 and variables named arguments or eval.

strictBuiltinIteratorReturn

This newest member (TypeScript 5.6) affects code that calls .next() on built-in iterators directly. When an iterator is finished, its result is { value: undefined, done: true }, so value might be undefined. Without the flag that undefined was typed any; with it, you must check done first:

TypeScript
const result = new Set(['a', 'b']).values().next();

console.log(result.value.toUpperCase());
// error TS18048: 'result.value' is possibly 'undefined'.

if (!result.done) {
  console.log(result.value.toUpperCase()); // fine: prints A
}

for...of loops and spreading handle this for you, so you'll mostly notice the flag in low-level iterator code (Iterators and Generators).

Beyond strict: two more flags

Two options are so useful that many teams treat them as part of strict mode, even though strict doesn't include them. Our editors leave both off, so you can see what goes wrong without them.

noUncheckedIndexedAccess

Indexing into an array or a dictionary might not find anything. Without this flag, TypeScript assumes it always does:

TypeScript An unchecked index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program compiles, then prints undefined and NaN. kiwi was typed number, so nothing stopped the calculation. With noUncheckedIndexedAccess, prices['kiwi'] has the type number | undefined, and kiwi * 3 becomes the error 'kiwi' is possibly 'undefined'. You then check first, or use ?? 0.

exactOptionalPropertyTypes

An optional property theme?: 'light' | 'dark' normally also accepts an explicit undefined. With this flag it means "absent, or one of the listed values", so { theme: undefined } becomes an error unless the type says theme?: 'light' | 'dark' | undefined. This matters for code that uses 'theme' in settings or Object.keys, as The tsconfig.json File demonstrates.

Start strict and stay strict. Turning strict on in a new project costs nothing. Turning it on in a large existing project can mean thousands of errors, which is why Migrating JavaScript to TypeScript shows how to enable the flags one at a time.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In strict mode, what does TypeScript say about const n = [3, 8].find((x) => x > 5); console.log(n.toFixed(1));?

    find returns number | undefined. strictNullChecks requires a check (or ?. / ??) before calling toFixed.
  2. 2. Which flag turns function area(w, h) { return w * h; } into a compile error?

    Without annotations, w and h would silently be any. noImplicitAny reports TS7006 for each parameter.
  3. 3. With strict on, what is the type of e in catch (e) { ... }?

    Any value can be thrown, so useUnknownInCatchVariables types it as unknown. Check it with instanceof Error before reading message.
  4. 4. type Fn = (x: string | number) => void; Does const f: Fn = (x: string) => {}; compile in strict mode?

    strictFunctionTypes requires the assigned function to accept every argument type the caller may pass.
  5. 5. Which option is NOT turned on by strict: true?

    noUncheckedIndexedAccess (and exactOptionalPropertyTypes) are separate options you enable yourself. Our editors leave them off.

Summary

  • "strict": true enables a family of checks: strictNullChecks, noImplicitAny, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, useUnknownInCatchVariables, noImplicitThis, alwaysStrict and strictBuiltinIteratorReturn.
  • strictNullChecks makes null and undefined separate types; check them with if, ?. or ??.
  • noImplicitAny forbids silent any, mostly on unannotated parameters (TS7006).
  • strictFunctionTypes and strictBindCallApply check callbacks and indirect calls properly; method-syntax parameters stay looser.
  • Class fields must be initialized (TS2564); caught errors are unknown (TS18046); this needs a known type (TS2683).
  • // @ts-expect-error marks a line that must have an error; it fails if the error disappears.
  • noUncheckedIndexedAccess and exactOptionalPropertyTypes aren't part of strict but close two more gaps.

Next: Primitive Types โ€” string, number, boolean, bigint, symbol, null and undefined in depth.