Tutorials / TypeScript: Beginner to Advanced / Strict mode and compiler flags that matter

Strict mode and compiler flags that matter

16 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. 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:

FlagWhat it does
noUncheckedIndexedAccessarray[i] and index-signature reads include undefined in the type
noImplicitReturnsEvery code path in a function must return a value
noFallthroughCasesInSwitchA case that runs into the next one is an error
noImplicitOverrideOverriding methods needs the override keyword
noUnusedLocals, noUnusedParametersFlag dead code. I often leave this to the linter
exactOptionalPropertyTypesx?: 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-error suppresses 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-ignore suppresses 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 strict flag with JavaScript's "use strict".**
  • Turning strict off when it gets annoying. The errors are the product.
  • **Using @ts-ignore.** Prefer @ts-expect-error with a reason.
  • **Adding any to make an error go away.** Use unknown and 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

  1. Create a project with strict off, write code that crashes on a missing property, then turn on strictNullChecks and watch the compiler find it.
  2. Turn on noUncheckedIndexedAccess and fix the errors in a small loop-based script.
  3. Write a class with an uninitialised property, read the error, and fix it in two different ways.
  4. Add a @ts-expect-error comment to a line with a real error, then fix the error and see what the compiler says about the comment.
typescript
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