Skip to the content

Lesson 105 of 296

Strict mode and strictNullChecks

What you will learn

  • What "strict": true turns on
  • noImplicitAny
  • strictNullChecks and the bugs it prevents
  • noUncheckedIndexedAccess
  • The non-null assertion ! and why to avoid it
  • Converting a JavaScript file to strict TypeScript
On this page

strict: true

In tsconfig.json, "strict": true turns on a group of checks that make TypeScript much safer. Always use it in new projects. Without it, TypeScript misses many real bugs.

The most important checks it enables:

OptionWhat it does
noImplicitAnyError when TypeScript cannot work out a type and would silently use any
strictNullChecksnull and undefined are separate types that must be handled
strictFunctionTypesStricter checking of function parameter types
strictPropertyInitializationClass properties must be given a value
useUnknownInCatchVariablesErrors in catch are unknown, not any
alwaysStrictOutputs JavaScript in strict mode

noImplicitAny

function greet(name) {           Error: Parameter 'name' implicitly has an 'any' type.
  return "Hi " + name;
}

Without this rule, name silently becomes any and nothing is checked.

strictNullChecks: the most valuable check

The famous "billion-dollar mistake" in programming is allowing null everywhere. Without strictNullChecks, every type silently includes null and undefined, so this compiles but crashes:

const user = users.find((u) => u.id === 7);
console.log(user.name);          crashes if no user is found

With strictNullChecks, find returns User | undefined, and TypeScript stops you:

console.log(user.name);          Error: 'user' is possibly 'undefined'.

You must handle the missing case:

if (!user) {
  throw new Error("User 7 not found");
}
console.log(user.name);          fine: TypeScript knows user exists here

or

console.log(user?.name ?? "Unknown");

strictNullChecks protects you from the most common JavaScript error: "Cannot read properties of undefined".

noUncheckedIndexedAccess

Not part of strict, but worth turning on. By default, array[i] is typed as the item type, even though the index might not exist:

const names: string[] = [];
const first = names[0];          type: string, but the value is undefined

With noUncheckedIndexedAccess, the type becomes string | undefined, so you must check. The same applies to index signatures and Records with string keys.

The non-null assertion !

! after a value tells TypeScript "trust me, this is not null or undefined":

const input = document.querySelector("input")!;

TypeScript removes null from the type, but nothing checks it at runtime. If you are wrong, the code crashes. Use it rarely, only when you are certain and a check would be pointless. Prefer a real check:

const input = document.querySelector("input");
if (!input) throw new Error("Input element missing");

Converting a JavaScript file to strict TypeScript

A task from the study plan. Steps:

  1. Rename .js to .ts.
  2. Turn on strict.
  3. Fix noImplicitAny errors: add parameter types.
  4. Define types or interfaces for the main data shapes.
  5. Fix null errors by adding real checks, not !.
  6. Replace any any with real types, or unknown plus checks.
  7. Run tsc --noEmit until there are zero errors.

Before:

function getTotal(items, discount) {
  const subtotal = items.reduce((sum, i) => sum + i.price * i.qty, 0);
  return discount ? subtotal - discount.amount : subtotal;
}

After:

type BasketItem = { pricePence: number; qty: number };
type Discount = { amountPence: number };

function getTotal(items: BasketItem[], discount?: Discount): number {
  const subtotal = items.reduce((sum, i) => sum + i.pricePence * i.qty, 0);
  return discount ? subtotal - discount.amountPence : subtotal;
}

Common mistakes

  • Turning strict off to make errors disappear.
  • Using ! everywhere instead of handling null.
  • Not knowing that find, querySelector and Map.get can return undefined or null.

How to say it in an interview

"I always enable strict mode. noImplicitAny stops values silently becoming any, and strictNullChecks makes null and undefined separate types that I must handle, which prevents the most common runtime error, reading a property of undefined. I also like noUncheckedIndexedAccess so array and record lookups include undefined. I avoid the non-null assertion because it is unchecked at runtime and prefer real checks or optional chaining."

Key words

WordMeaning
strict modeA group of stricter compiler checks
noImplicitAnyError when a type would silently be any
strictNullChecksnull and undefined must be handled explicitly
noUncheckedIndexedAccessIndex lookups include undefined in their type
Non-null assertion!: telling TypeScript a value is not null, without checking

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.