Strict mode and compiler flags that matter
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
What strict actually means
"strict": true in tsconfig.json is a shortcut that turns on a group of checks. TypeScript can be used without it, and many tutorials do so, but then it is much more forgiving and finds far fewer bugs. For a new project, there is no good reason to leave it off. For an old one, you can turn on the flags one by one, as the migration lesson explains.
Here are the flags that strict enables, and what each one gives you.
noImplicitAny
Without a type, a parameter silently becomes any. With this flag, it is an error, and you must write a type or let it be inferred.
// Error: Parameter 'x' implicitly has an 'any' type.
function double(x) {
return x * 2;
}
function double(x: number): number {
return x * 2;
}
console.log(double(4));
This one is the heart of strict mode. It stops any from spreading without you noticing.
strictNullChecks
This is the most valuable flag. Without it, null and undefined can be assigned to every type, and the famous "cannot read properties of undefined" crashes are not caught. With it, they are separate types, and you must handle them.
interface User {
name: string;
email?: string;
}
function emailDomain(user: User): string {
// return user.email.split("@")[1]; // Error: 'user.email' is possibly 'undefined'
if (!user.email) {
return "no email";
}
return user.email.split("@")[1] ?? "invalid email";
}
console.log(emailDomain({ name: "Ali", email: "ali@example.com" })); // example.com
console.log(emailDomain({ name: "Sara" })); // no email
The commented-out line is the typical bug. With strict null checks, TypeScript makes you decide what happens when the value is missing. A very large share of runtime errors in JavaScript apps are of this kind.
A related tool is the non-null assertion !, as in user.email!. It tells the compiler "I know it is not null". Like as, it is unchecked, and a wrong guess crashes at runtime. Use it rarely, and only where you can explain why it is true.
strictFunctionTypes and strictBindCallApply
strictFunctionTypes makes function parameter types checked more strictly when you assign one function to another. strictBindCallApply checks that bind, call and apply get the right arguments. You rarely think about them, but they close real holes.
function greet(name: string, age: number): string {
return `${name} is ${age}`;
}
const greetSara = greet.bind(null, "Sara");
console.log(greetSara(28));
// greetSara("old"); // Error with strictBindCallApply
strictPropertyInitialization
Class properties must be assigned in the constructor, or have an initial value:
class Session {
token: string; // must be set in the constructor
attempts = 0; // has a default
note?: string; // optional, so fine
constructor(token: string) {
this.token = token;
}
}
console.log(new Session("abc").token);
If you leave token unset, the compiler reports "Property 'token' has no initializer and is not definitely assigned in the constructor". It prevents objects that exist in a half-built state.
noImplicitThis and useUnknownInCatchVariables
noImplicitThis complains when this would be any, which happens in loose function code. useUnknownInCatchVariables makes the error in catch (error) an unknown, so you must check it, as we did in the last lesson.
function describeError(error: unknown): string {
if (error instanceof Error) return error.message;
return "Unknown error";
}
try {
JSON.parse("{ bad");
} catch (error) {
console.log(describeError(error));
}
alwaysStrict
This emits "use strict" in the generated JavaScript, and parses your code in JavaScript's strict mode. Do not confuse it with the TypeScript strict flag. They are separate things with an unlucky shared name.
Flags worth adding beyond strict
The strict family does not include everything useful. These are the ones I add to every new project:
| Flag | What it does |
|---|---|
noUncheckedIndexedAccess | array[i] and index-signature reads include undefined in the type |
noImplicitReturns | Every code path in a function must return a value |
noFallthroughCasesInSwitch | A case that runs into the next one is an error |
noImplicitOverride | Overriding methods needs the override keyword |
noUnusedLocals, noUnusedParameters | Flag dead code. I often leave this to the linter |
exactOptionalPropertyTypes | x?: string means "absent or a string", not "or undefined". Stricter, and sometimes noisy |
noUncheckedIndexedAccess in practice
Without the flag, TypeScript pretends that every array index exists:
const names: string[] = ["Ali", "Sara"];
const third = names[2]; // with the flag: string | undefined
// console.log(third.toUpperCase()); // Error with the flag: possibly undefined
console.log(third?.toUpperCase() ?? "no third name");
const scores: Record<string, number> = { ali: 90 };
const missing = scores["zara"]; // number | undefined with the flag
console.log(missing ?? 0);
This reflects reality. names[2] really is undefined. The flag makes code a little more verbose, but it removes a whole class of "undefined is not an object" errors. When you loop with for...of or use map, you never need these checks, because the items are known to exist.
Escape hatches, and how to use them
Sometimes you cannot satisfy the compiler, for example because of a bad third-party type. TypeScript gives you comments:
// @ts-expect-errorsuppresses an error on the next line, and fails the build if there is no error there any more. This is the right choice, because the suppression cleans itself up when the problem is fixed.// @ts-ignoresuppresses errors silently with no such check. I avoid it.- Always add a short reason after the comment.
// @ts-expect-error: the library types are missing the 'timeout' option
client.connect({ timeout: 500 });
Turning strict on gradually
For an existing project, you do not have to fix everything in one go. Turn on one flag at a time, starting with noImplicitAny, fix the errors, commit, then strictNullChecks, which usually has the most to fix, and so on. Once all are on, replace them with "strict": true.
Common mistakes
- **Using
!everywhere to silence null errors.** It is an unchecked promise. - **Confusing the
strictflag with JavaScript's"use strict".** - Turning strict off when it gets annoying. The errors are the product.
- **Using
@ts-ignore.** Prefer@ts-expect-errorwith a reason. - **Adding
anyto make an error go away.** Useunknownand narrow, or fix the type. - Forgetting that the new flags can add errors after a TypeScript upgrade. Read the release notes before changing the version.
Try it yourself
- Create a project with
strictoff, write code that crashes on a missing property, then turn onstrictNullChecksand watch the compiler find it. - Turn on
noUncheckedIndexedAccessand fix the errors in a small loop-based script. - Write a class with an uninitialised property, read the error, and fix it in two different ways.
- Add a
@ts-expect-errorcomment to a line with a real error, then fix the error and see what the compiler says about the comment.
interface User {
name: string;
email?: string;
}
function emailDomain(user: User): string {
// return user.email.split("@")[1]; // Error: 'user.email' is possibly 'undefined'
if (!user.email) {
return "no email";
}
return user.email.split("@")[1] ?? "invalid email";
}
console.log(emailDomain({ name: "Ali", email: "ali@example.com" })); // example.com
console.log(emailDomain({ name: "Sara" })); // no email
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account