Skip to content
Visual explainer 1h 30m to learn 3 steps

tsconfig & strict mode

Configure a strict TypeScript project and fix the errors it reveals.

By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.

Topic 12 of 36

In short

tsconfig.json controls how TypeScript checks and compiles your project. Turning on strict mode enables the checks that catch the most real bugs, especially around null and undefined.

Explained simply

Every TypeScript project has a tsconfig.json file at its root. It tells the compiler which files to check, how strict to be, and which version of JavaScript and which browser or Node features to expect.

The most important setting is strict. With strict turned off, TypeScript is very forgiving: values it cannot figure out quietly become any, and null can slip in anywhere. Many real bugs, like reading a field of undefined, are never reported.

Turning on strict makes TypeScript point out those risky places. At first you see more errors. But each error is a spot where your app could crash for a real user. Fixing them before release is much cheaper than fixing them after a bug report.

In modern frontend projects, such as Next.js or Vite apps, TypeScript usually only checks your code. Another fast tool removes the types and builds the bundle. That is why the config often says noEmit: true, and why you should run the type check in CI as its own step.

Press Play on a diagram to walk through it one step at a time.

CompareWithout vs with strict mode
strict: false
  • Missing types silently become any
  • null can go anywhere
  • Bugs surface at runtime
  • Fewer errors, false confidence
strict: true
  • noImplicitAny flags untyped params
  • strictNullChecks forces null handling
  • Bugs surface in the editor
  • More errors up front, safer code
FlowTurning on strict in an existing project
  1. 1
    Baseline

    Run tsc --noEmit and note the error count

  2. 2
    One flag

    Enable noImplicitAny first, then strictNullChecks

  3. 3
    Fix by folder

    Small pull requests, shared code first

  4. 4
    Full strict

    Replace the single flags with strict: true

  5. 5
    Lock it in

    Type check in CI so errors cannot come back

In depth

What strict actually turns on

strict is a shortcut for a family of flags. The two you will notice most are noImplicitAny, which errors when a parameter or variable would silently become any, and strictNullChecks, which keeps null and undefined out of every type unless you write them in.

Others matter too. strictFunctionTypes checks callback parameter types properly. strictPropertyInitialization requires class fields to be set in the constructor. useUnknownInCatchVariables makes the error in catch (err) unknown instead of any, so you must check err instanceof Error before reading err.message. New strict checks are added in some TypeScript releases, so upgrading TypeScript can reveal new errors in a strict project. That is expected and usually worth it.

  • noImplicitAny
  • strictNullChecks
  • strictFunctionTypes and strictBindCallApply
  • strictPropertyInitialization
  • useUnknownInCatchVariables and alwaysStrict

Who type checks and who builds

In a Next.js or Vite project, three tools touch your TypeScript. The editor runs the TypeScript language service for red squiggles as you type. A fast transpiler, SWC in Next.js or esbuild in Vite, strips the types file by file without checking them, so builds stay fast. And tsc --noEmit checks the whole project without writing any files.

Because the transpiler sees one file at a time, isolatedModules: true is required: it flags code that needs whole-program knowledge to compile, such as re-exporting a type without the type keyword. Next.js runs a type check during next build, but a separate tsc --noEmit step in CI catches errors earlier and gives cleaner output.

LayersTypeScript in a bundled frontend project
  1. 1
    Editor language service

    Instant errors and autocomplete as you type

  2. 2
    tsc --noEmit

    Whole-project type check in CI, writes nothing

  3. 3
    SWC or esbuild

    Strips types per file, no checking

  4. 4
    Bundler output

    Plain JavaScript shipped to browsers

target, lib, module and moduleResolution

target sets which JavaScript syntax the output uses; ES2022 is a safe modern choice. lib lists the built-in APIs TypeScript knows exist: include "dom" for browser code, and leave it out for pure Node code so you cannot accidentally use window. Note that lib only describes APIs; it does not add polyfills.

module and moduleResolution decide how imports are read. For apps built by a bundler, use module "esnext" with moduleResolution "bundler", which allows imports without file extensions. For code run directly by Node.js, use "nodenext" for both, which follows Node's real rules, including required .js extensions in ESM imports.

  • Bundled app: module esnext, moduleResolution bundler
  • Node.js library or server: module and moduleResolution nodenext
  • jsx: preserve lets Next.js handle JSX itself

Checks beyond strict

A few useful flags are not part of strict. noUncheckedIndexedAccess adds undefined to every array index and dictionary lookup, so items[0] is Item | undefined. This catches the classic empty-array crash. exactOptionalPropertyTypes separates a missing field from one set to undefined. noImplicitReturns errors when some paths of a function return a value and others do not. noFallthroughCasesInSwitch catches a forgotten break.

Turn these on in new projects. In an old codebase, add one at a time and fix its errors before the next. paths sets import aliases such as "@/*": ["./src/*"], so you can write import { db } from "@/lib/db" instead of long ../../ chains; Next.js reads these aliases automatically.

Fixing the errors strict reveals

Most strict errors fall into a few patterns. "Object is possibly undefined": add an early return, optional chaining (user?.name), or a default with ??. "Parameter implicitly has an any type": add an annotation. "err is of type unknown": check err instanceof Error first. "Property has no initializer": set it in the constructor or give it a default.

Avoid fixing errors with the non-null assertion ! or as any. They make the error go away without making the code safer. When you truly cannot fix a line yet, prefer // @ts-expect-error with a comment over // @ts-ignore: expect-error itself fails once the underlying problem is fixed, so stale suppressions do not pile up.

CompareCommon strict error: quick fix vs real fix
Silencing
  • user!.name
  • (data as any).items
  • // @ts-ignore
  • Error hidden, crash still possible
Handling
  • if (!user) return null;
  • Validate data, then use items
  • // @ts-expect-error with a reason
  • Error gone because the case is covered

Learn it in 3 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Read the key tsconfig options~30m
  2. 2
    Enable strict mode~30m
  3. 3
    Fix the errors strict mode reveals~30m

Key points

  • Start new projects with strict: true; it is much harder to enable later.
  • strictNullChecks makes you handle values that may be null or undefined.
  • target and lib decide which JavaScript features and APIs are available.
  • Fix strict errors with narrowing and real types, not non-null assertions everywhere.

Key terms

Tap a card to flip it. 0/5 known

Examples

json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["dom", "ES2022"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": ["src"]
}

A strict config for a bundled frontend project.

Fixing three strict errors in one function

This function compiled without strict. With strict on, TypeScript reports three problems. Step 1: users is an implicit any, so annotate it. Step 2: find can return undefined, so handle the not-found case instead of reading .name blindly. Step 3: err in catch is unknown, so check it is an Error before reading message. Each fix covers a real crash path.

ts
type User = { id: number; name: string };

function nameOf(users: User[], id: number): string {
  const user = users.find((u) => u.id === id);
  if (!user) return "Unknown user";
  return user.name;
}

try {
  JSON.parse("{bad json");
} catch (err) {
  const msg = err instanceof Error ? err.message : String(err);
  console.error(msg);
}

noUncheckedIndexedAccess catches an empty list

A dashboard shows the latest order with orders[0].total. When a new user has no orders, this crashes. Step 1: enable noUncheckedIndexedAccess in tsconfig. Step 2: TypeScript now types orders[0] as Order | undefined and flags .total. Step 3: handle the empty case. The same applies to lookups in a dictionary object: prices["sku-1"] might be missing.

ts
// tsconfig: "noUncheckedIndexedAccess": true
type Order = { id: number; total: number };

function latestTotal(orders: Order[]): number {
  const latest = orders[0]; // Order | undefined
  return latest?.total ?? 0;
}

const prices: { [sku: string]: number } = { "sku-1": 999 };
const p = prices["sku-2"]; // number | undefined
console.log(p ?? "not found");

Quick reference

  • "strict": true enables noImplicitAny, strictNullChecks and the rest of the strict family
  • npx tsc --noEmit type checks the whole project without writing files
  • Bundled apps: "module": "esnext" with "moduleResolution": "bundler"
  • Node.js without a bundler: "module" and "moduleResolution": "nodenext"
  • "noUncheckedIndexedAccess": true makes arr[0] possibly undefined
  • "paths": { "@/*": ["./src/*"] } gives you clean import aliases
  • Prefer // @ts-expect-error over // @ts-ignore; it fails once the error is fixed
  • "skipLibCheck": true skips checking .d.ts files in node_modules for faster builds

Common mistakes

  • Silencing strict errors with ! or as any instead of handling the case.
  • Disabling strict for the whole project because of a few hard files.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your Vite app builds even though there are type errors. Why?

Question 2

2With useUnknownInCatchVariables (part of strict), what is the type of err in catch (err)?

Question 3

3Which flag makes items[0] have type Item | undefined?

Question 4

4What does adding "dom" to lib do?

Question 5

5Why is // @ts-expect-error usually better than // @ts-ignore?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Add a typecheck script to package.json that checks the project without emitting files, and run it.

  2. Exercise 2medium

    This compiles without strict but fails with it: function total(items) { return items.reduce((s, i) => s + i.price, 0); } and const first = document.querySelector("input").value. Rewrite both so they pass strict.

  3. Exercise 3hard

    Write a tsconfig.json for a Next.js-style app: strict, no emit, bundler resolution, unchecked index access on, JSX preserved, an @/* alias to ./src/*, and isolated modules.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I turn on strict mode in TypeScript?
Yes for every new project. For an old one, enable the strict flags one at a time and fix errors folder by folder.
What does skipLibCheck do and is it safe?
It skips type checking of declaration files (.d.ts), mostly in node_modules. It speeds up builds and avoids errors in third-party types; your own code is still fully checked.
Why does my code run even though tsc shows errors?
Most build tools strip types without checking them, and tsc also writes output by default even when errors exist. Run tsc --noEmit as a separate CI step so errors fail the build.

Go deeper

ShareXLinkedInWhatsApp