Lesson 105 of 296
Strict mode and strictNullChecks
What you will learn
- What
"strict": trueturns 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:
| Option | What it does |
|---|---|
noImplicitAny | Error when TypeScript cannot work out a type and would silently use any |
strictNullChecks | null and undefined are separate types that must be handled |
strictFunctionTypes | Stricter checking of function parameter types |
strictPropertyInitialization | Class properties must be given a value |
useUnknownInCatchVariables | Errors in catch are unknown, not any |
alwaysStrict | Outputs 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 foundWith 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 hereor
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 undefinedWith 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:
- Rename
.jsto.ts. - Turn on
strict. - Fix
noImplicitAnyerrors: add parameter types. - Define types or interfaces for the main data shapes.
- Fix null errors by adding real checks, not
!. - Replace any
anywith real types, orunknownplus checks. - Run
tsc --noEmituntil 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
strictoff to make errors disappear. - Using
!everywhere instead of handlingnull. - Not knowing that
find,querySelectorandMap.getcan 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
| Word | Meaning |
|---|---|
| strict mode | A group of stricter compiler checks |
| noImplicitAny | Error when a type would silently be any |
| strictNullChecks | null and undefined must be handled explicitly |
| noUncheckedIndexedAccess | Index 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.