Skip to content
FEE
Frontend Engineering Essentials
Entry Level

tsconfig & Strict Mode ​

tsconfig.json is the TypeScript compiler's configuration file. It governs which files are included in compilation, which JavaScript version is emitted, how module imports are resolved, and which type checks are enforced. The file is the single authoritative source of truth for a project's TypeScript behavior — its contents determine what errors the compiler catches, what JavaScript the compiler produces, and how seamlessly the project integrates with editors, bundlers, and CI pipelines.

Most projects need fewer than twenty tsconfig.json options to achieve a correct, productive setup. The surface area of the tsconfig reference is large — dozens of options spanning language features, output control, module resolution, and diagnostic behavior — but the vast majority can be left at their defaults. Understanding the ten options that matter most, and knowing why the common misconfiguration mistakes exist, prevents the silent type-check gaps that undermine TypeScript's value. A misconfigured tsconfig does not produce a compiler error about the misconfiguration itself; the compiler simply fails to catch errors it would have caught with correct settings.

The most consequential configuration decisions cluster around two concerns: strictness and module resolution. Strictness controls how aggressively the compiler checks for null dereferences, implicit any, and function argument variance. Module resolution controls how the compiler interprets import paths and whether its understanding of those paths matches the runtime or bundler. Both concerns have correct answers that apply to virtually every project, and both are frequently misconfigured in ways that are invisible until a bug surfaces at runtime. The invisibility is what makes them dangerous: neither misconfiguration produces a compiler error about itself.

A third concern, project references, becomes relevant when a codebase grows to multiple packages in a monorepo. Project references allow TypeScript to understand the dependency graph across packages, enable incremental compilation, and produce accurate cross-package types without requiring every package to be compiled together. Like strictness and module resolution, project references have a correct setup that is not immediately obvious, and the cost of getting it wrong — silent build ordering problems or stale types across package boundaries — is paid in debugging time rather than compiler errors.

Design Thinking ​

The strict flag as a unit ​

strict: true is not a single compiler check — it is an umbrella that enables a group of related checks together. In TypeScript 5.x, the umbrella covers noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, alwaysStrict, and useUnknownInCatchVariables. Each of these checks addresses a distinct category of type-safety gap. noImplicitAny prevents variables from silently receiving the any type when TypeScript cannot infer a more specific type; without it, every untyped parameter becomes any and the type system's guarantees collapse silently. strictNullChecks prevents null and undefined values from flowing into positions that expect a concrete value; without it, every type implicitly includes null | undefined and the compiler cannot flag the null dereferences that cause the majority of JavaScript runtime exceptions. strictFunctionTypes enforces contravariance on function parameter types rather than allowing the unsound covariance that TypeScript's early type system permitted for backward compatibility.

The umbrella design is intentional and forward-looking. As TypeScript adds new strict checks in future versions, they are added under strict: true automatically. A project that enables strict: true opts into future type-safety improvements when it upgrades TypeScript, without needing to enumerate every new flag explicitly. A project that enables individual flags and omits the umbrella is frozen at the checks it explicitly listed. When TypeScript 5.2 adds a new strict check, that project's upgrade does not include the check; the new category of error goes undetected, and the team cannot know what they are missing because the tsconfig appears complete.

Disabling specific strict flags to silence errors on a project that already has strict: true is a form of type debt that compounds over time. Once the team learns that individual strict flags can be disabled, the pattern spreads: each engineer who encounters an inconvenient strict error disables the relevant flag rather than fixing the underlying code, and the set of disabled checks grows. After several such decisions, the project has strict: true at the top level but a collection of noImplicitAny: false and strictNullChecks: false overrides that cancel most of its effect. The tsconfig reads as strict while providing almost none of the protection. The correct response to a strict-mode error is always to fix the code that the error identified — the error is the compiler reporting that the declared types do not accurately describe the runtime behavior.

The practical implication for onboarding a legacy codebase to strict mode is that enabling strict: true on an existing project typically produces hundreds or thousands of errors on first run. The recommended approach is to enable strict mode in a separate tsconfig used only for new files, and migrate existing files incrementally by moving them into the strict-mode config's include patterns. TypeScript's @ts-expect-error directive can mark known pre-existing errors for later resolution without suppressing the check globally. The path to full strict mode is manageable when it is treated as a migration project with tracked progress rather than a flag that must be flipped atomically.

Module resolution: the source of most configuration confusion ​

The moduleResolution option controls how TypeScript interprets import paths when it searches for the types corresponding to an import statement. This option must be set independently from the module option, which controls the format of JavaScript that TypeScript emits. The two options interact but are not the same: module: "ESNext" does not imply moduleResolution: "bundler", and setting one without explicitly setting the other leaves the second at its default, which may not match the project's environment. The combination of module and moduleResolution must be consistent: TypeScript will produce a diagnostic if the combination is contradictory, but will not produce a diagnostic if the combination is merely suboptimal for the project's runtime.

The legacy "node" resolution algorithm was designed for CommonJS module systems as they existed in early Node.js. It searches node_modules by traversing parent directories, treats directory imports as pointing to the directory's index.js, and reads package.json main fields. It does not read exports fields. The exports field in package.json is how modern packages expose different module entry points for different environments — ESM versus CommonJS, browser versus Node, development versus production. When TypeScript uses "node" resolution and a package uses exports as its primary API surface, TypeScript may resolve to the wrong entry point or fail to find the package at all, while the bundler — which does read exports — resolves correctly. The result is a codebase that bundles and runs correctly while producing spurious TypeScript errors, or, more dangerously, one where TypeScript resolves to a different entry point than the bundler and imports appear to type-check successfully against stale or incorrect types.

"bundler" resolution, introduced in TypeScript 5.0, models how bundlers like Vite and webpack actually resolve imports. It reads exports fields, understands conditional exports, and allows extension-less relative imports because the bundler adds the extension. This is the correct choice for frontend projects and any fullstack project where a bundler mediates between TypeScript source and the runtime. "node16" and "nodenext" model Node.js's own ESM resolution algorithm, which also reads exports fields but requires explicit file extensions in relative imports, matching Node.js's own requirement for ESM. The correct choice between "bundler" and "node16" depends entirely on whether module resolution at runtime is performed by a bundler or by Node.js directly.

Setting moduleResolution correctly is the single most effective step for eliminating false "module not found" errors in modern TypeScript projects. A secondary but important step is ensuring that module is set consistently with moduleResolution. For a Vite project using "bundler" resolution, module: "ESNext" is correct. For a Node.js project using "node16" resolution, module: "Node16" or "NodeNext" is correct. Mixing these — such as module: "CommonJS" with moduleResolution: "bundler" — may produce TypeScript errors or silent behavior differences, because the emitted JavaScript format does not match the resolution model's assumptions about how imports work at runtime.

The module and moduleResolution interaction is the source of most "it works in the bundler but TypeScript complains" errors reported on GitHub and Stack Overflow. When a team upgrades to a modern package that uses exports and suddenly TypeScript cannot find it, the fix is almost never to downgrade the package — it is to upgrade moduleResolution to "bundler" or "node16". Once that change is made, the entire class of false-negative import errors disappears, and the project's TypeScript configuration accurately models what the runtime will do.

This alignment between TypeScript's resolution model and the bundler's resolution model is also the prerequisite for accurate type-checking of conditional exports — packages that expose different APIs for ESM and CommonJS consumers — since "bundler" resolution follows the import condition in exports maps while "node" resolution ignores them entirely.

Project references for monorepos ​

Large codebases with multiple packages — a design system library, shared utility packages, and one or more application packages — face a TypeScript compilation challenge that a single tsconfig cannot solve efficiently. If every package is included in a single compilation, TypeScript must process all source files in all packages together. This eliminates the possibility of incremental builds at the package boundary, makes it impossible to enforce visibility rules between packages, and causes compilation time to grow with the total size of the codebase rather than with the size of what changed. For a monorepo with ten packages totaling a hundred thousand lines, a change to a utility function in one package triggers a full recompile of all ten packages.

If each package has its own tsconfig and is compiled independently, TypeScript does not understand the dependency relationships between packages and cannot provide accurate cross-package type checking without requiring each package to be pre-compiled before its consumers are checked. This produces a workflow where engineers must run tsc in each package in dependency order before the downstream packages can be type-checked — a manual process that is both error-prone and slow.

TypeScript project references solve both problems. Each package has its own tsconfig.json with composite: true enabled. The composite flag instructs TypeScript to emit .d.ts declaration files alongside compiled output and store a .tsbuildinfo file that records the compilation state for incremental builds. The root tsconfig lists each package as a reference via the references array. When the compiler processes a downstream package, it reads the referenced upstream packages' pre-built declaration files rather than reprocessing their source. This means that changing a file in one package only requires recompiling that package and the packages that transitively depend on it — not the entire monorepo.

Project references also enable build ordering through tsc --build mode, which reads the reference graph and determines the correct compilation order. This eliminates the category of build failures where a downstream package compiles before its upstream dependency has been built. tsc --build --watch extends this to incremental watch mode: it monitors file changes across all packages and recompiles only the affected subgraph, making the inner development loop as fast as if the entire monorepo were a single package while maintaining package-boundary isolation.

The paths option in tsconfig.json complements project references by enabling import aliases that resolve to package source directories during development. When the TypeScript language server follows @design-system/components to source (via paths) rather than to compiled output, go-to-definition navigation and rename refactoring work correctly across package boundaries. At build time, tsc --build uses the compiled declaration files from project references; the paths mapping is for the development experience only. Understanding this distinction — paths for the language server, references for the build — is the key to a monorepo TypeScript setup where both the editor experience and the build output are correct.

Best Practices ​

MUST enable strict: true in every project tsconfig.json and never disable it by enabling individual flags without the umbrella. Strict mode is the minimum threshold at which TypeScript's type system catches the bugs it was designed to catch — null dereferences, implicit any, function argument variance. Disabling specific checks to silence errors is a form of type debt that compounds: once the team learns that strict checks can be disabled, the pattern spreads. Each disabled check is a category of bug that the compiler will no longer catch, permanently, for as long as the check remains disabled. When migrating a legacy codebase, use a phased approach — strict mode in a separate config for new files — rather than disabling checks globally.

MUST set moduleResolution to "bundler" for projects using Vite, webpack, or another bundler, and to "node16" or "nodenext" for projects running directly on Node.js. The legacy default "node" resolution does not understand exports fields in package.json, causing TypeScript to resolve imports differently than the bundler or runtime does. This mismatch produces false "module not found" errors for packages that use exports fields, and — more dangerously — causes TypeScript to type-check against a different entry point than the one the bundler actually loads. The runtime bug that results has no compiler warning preceding it; both the compiler and the bundler report success while the types in use do not correspond to the code that runs.

SHOULD keep tsconfig.json at the project root and use extends to share a base configuration across packages in a monorepo. A shared base config (tsconfig.base.json) captures common options — strict, target, lib, moduleResolution — in one place. Package-level configs extend the base and add package-specific options such as outDir, rootDir, and paths. This prevents option drift across packages: if the base config is the authoritative source for strictness and resolution settings, there is no opportunity for one package to silently disable a check that all other packages enforce. When the base config is updated, all packages receive the change on their next build, keeping the entire monorepo's TypeScript behavior coherent.

SHOULD use paths in tsconfig.json to define import aliases and keep them synchronized with the bundler's alias configuration. Import aliases such as @/components/Button must be declared in both tsconfig.json (so TypeScript can resolve the type for the import) and the bundler config (so the bundler can resolve the module at build time). When these two configurations fall out of sync — because one was updated and the other was not — TypeScript accepts the import as type-safe while the bundler rejects it at build time. Treating both configurations as a single unit that changes together, ideally by co-locating the alias definitions or validating their consistency in CI, prevents this class of mismatch from reaching production.

Visual ​

The following diagram shows the module resolution decision tree for a TypeScript import, contrasting "node" (legacy) resolution with "bundler" (modern) resolution. The key divergence is the exports field check: legacy resolution skips it entirely, which causes the mismatch with modern packages that use conditional exports to serve different entry points per environment.

The red path is not a compile error — it is a successful compilation that resolves to the wrong module entry. This is why moduleResolution: "node" in a modern project that consumes packages with exports fields is dangerous rather than merely inconvenient: the compiler reports no error while the types in use may not match the module the bundler actually loads. The yellow path indicates resolution that succeeded but used a fallback that may not reflect the package's intended API for the current environment.

A practical diagnostic for identifying this class of misconfiguration: if the project uses moduleResolution: "node" and installs any package that was published in the last two to three years by an actively maintained library, examine that package's package.json for an exports field. If the field is present and the TypeScript types or typings field in the package points to a different path than what exports specifies for the import condition, TypeScript is resolving against a different entry point than the bundler. The fix is to upgrade moduleResolution to "bundler" or "node16" — not to manually override the package's type resolution.

Example ​

The following example shows a realistic monorepo configuration: a shared base config, a library package config, and an application package config using Vite. This structure enables strict type checking, correct module resolution, and cross-package type safety via project references.

The base configuration lives at the monorepo root and captures all options shared across packages. Every package in the monorepo extends this file, which means that changing strict or moduleResolution here propagates everywhere:

json
// tsconfig.base.json (monorepo root)
{
  "compilerOptions": {
    "strict": true,
    "target": "ES2022",
    "lib": ["ES2022"],
    "moduleResolution": "bundler",
    "module": "ESNext",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "declaration": true,
    "declarationMap": true
  }
}

The library package extends the base and adds package-specific output settings. The composite: true flag is required for project references to work — it instructs TypeScript to emit declaration files alongside output and store a build manifest that enables incremental builds:

json
// packages/ui/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "composite": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "paths": {
      "@ui/*": ["./src/*"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

The application package extends the base, references the library package, and adds application-specific options. The references array tells TypeScript to use the library package's pre-built declaration files when type-checking the application:

json
// packages/app/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src",
    "paths": {
      "@ui/*": ["../ui/src/*"],
      "@/*": ["./src/*"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"],
  "references": [
    { "path": "../ui" }
  ]
}

The root tsconfig enumerates all packages as references. This is what enables tsc --build to determine the correct compilation order and compile the entire monorepo incrementally:

json
// tsconfig.json (monorepo root)
{
  "files": [],
  "references": [
    { "path": "./packages/ui" },
    { "path": "./packages/app" }
  ]
}

For the Vite application, the bundler config must mirror the paths aliases defined in tsconfig.json. The two configs are a matched pair: TypeScript uses paths for type resolution; Vite uses alias for module resolution at build time. When they diverge, the project enters a split-brain state where TypeScript and Vite disagree on what an import resolves to:

typescript
// packages/app/vite.config.ts
import { defineConfig } from 'vite';
import path from 'path';
// __dirname is not available in ESM; use import.meta.dirname (Node 20.11+ / Vite 5+)
const __dirname = import.meta.dirname;

export default defineConfig({
  resolve: {
    alias: {
      // Must match tsconfig.json paths exactly
      '@ui': path.resolve(__dirname, '../ui/src'),
      '@': path.resolve(__dirname, './src'),
    },
  },
});

A TypeScript source file in the application imports from both aliases, and both resolve correctly in TypeScript and Vite because the alias definitions are synchronized:

typescript
// packages/app/src/features/Dashboard.tsx
import { Button } from '@ui/components/Button';   // resolves via project reference + paths alias
import { useTheme } from '@/hooks/useTheme';       // resolves via local paths alias

export function Dashboard() {
  const theme = useTheme();
  return (
    <div style={{ background: theme.background }}>
      <Button variant="primary">Get Started</Button>
    </div>
  );
}

The @ui/components/Button import is typed against the library's TypeScript source (through the paths mapping in the app's tsconfig, used by the language server) and resolved via the pre-compiled declaration file in packages/ui/dist during tsc --build (through the project reference). Changes to the library's source trigger an incremental rebuild of the library package and then the application package, but not any other unrelated packages in the monorepo.

For single-package projects not using a monorepo, the tsconfig is simpler but the same two principles apply. A Vite project needs strict: true and moduleResolution: "bundler", and should set target and lib to reflect the environments it actually needs to support. Setting target higher (e.g., "ES2022") means TypeScript will not downlevel modern syntax like optional chaining or nullish coalescing, because those constructs are natively available in the target environment. Setting lib controls which browser and DOM APIs TypeScript considers available; a project that targets only Node.js should use "lib": ["ES2022"] without DOM types, and a browser project should use "lib": ["ES2022", "DOM", "DOM.Iterable"].

To illustrate what strict mode catches that a non-strict configuration misses, consider a function that processes user input. With strict: true, TypeScript enforces that nullable inputs must be checked before use:

typescript
// With strict: true, TypeScript enforces null safety throughout
function formatUserName(user: { firstName: string; lastName: string | null }): string {
  // Error: Object is possibly 'null' — strictNullChecks catches this
  // return `${user.firstName} ${user.lastName.trim()}`;

  // Correct: check for null before accessing
  const last = user.lastName ? ` ${user.lastName.trim()}` : '';
  return `${user.firstName}${last}`;
}

// With strict: true, TypeScript catches implicit any in parameters
function processItems(items) { // Error: Parameter 'items' implicitly has an 'any' type
  return items.map((item) => item.id); // item is also any — type safety lost
}

// Corrected version
function processItemsTyped(items: Array<{ id: string }>): string[] {
  return items.map((item) => item.id); // item.id is correctly typed as string
}

The following example shows a phased strict mode migration setup. When enabling strict: true on an existing project is not feasible in a single step, a separate tsconfig for new code provides a migration path. New files are placed under src/new/ (or the pattern appropriate for the project) and are covered only by the strict config. Existing files continue to compile under the legacy config until they are individually migrated:

json
// tsconfig.strict.json — used for new code
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true
  },
  "include": [
    "src/new/**/*",
    "src/utils/**/*"
  ]
}
json
// tsconfig.json — legacy config for existing code
{
  "compilerOptions": {
    "target": "ES2022",
    "moduleResolution": "bundler",
    "module": "ESNext",
    "strict": false,          // defer remaining strict flags during migration
    "noImplicitAny": true     // keep this one active throughout
  },
  "include": ["src/**/*"],
  "exclude": ["src/new/**/*", "src/utils/**/*"]
}

CI runs both tsc --project tsconfig.strict.json --noEmit and tsc --project tsconfig.json --noEmit. New code must satisfy the strict config; existing code is migrated file by file, moving each file from the legacy include to the strict include once its errors are fixed. When all files have been migrated, tsconfig.json is deleted and tsconfig.strict.json becomes the only config.

Common Mistakes ​

Setting strict: false or individually disabling specific strict flags to silence errors defers type debt rather than resolving it. The errors that strict: true surfaces are not false positives — they identify code where the declared types do not accurately describe runtime behavior. Disabling strictNullChecks to avoid nullable-type errors means the compiler will no longer flag the null dereferences that are among the most common sources of runtime exceptions in TypeScript codebases. The errors disappear from the build output; the bugs remain in the code. This mistake is particularly damaging in large codebases because the accumulated type debt makes it progressively harder to re-enable strict mode later: each re-enabled check surfaces a category of latent bugs that has been accumulating since the check was disabled, and the team must now audit and fix a much larger surface area than they would have faced if they had maintained strict mode from the start.

Using "module": "commonjs" with "moduleResolution": "node" in a project that consumes modern ESM packages prevents TypeScript from reading exports fields in those packages' package.json. This combination was the standard configuration for Node.js projects in the CommonJS era, and many project templates and tutorials still recommend it. In a modern project that installs packages relying on exports for their primary entry points, this combination causes TypeScript to either fail to find the package at all or resolve to a stale main field entry that does not reflect the package's current API. The bundler, which uses its own resolution logic and does read exports, loads the correct entry point; TypeScript's types come from a different, older entry. The resulting mismatch — TypeScript reports no error, but the types in use do not correspond to the code that runs — is one of the hardest categories of bug to diagnose because both the compiler and the bundler report success, and the discrepancy only becomes visible when a runtime value does not have the shape TypeScript claimed it would.

Forgetting to synchronize paths aliases between tsconfig.json and the bundler configuration creates a split-brain state where TypeScript and the bundler disagree on what an import resolves to. When tsconfig.json defines "@/components": ["./src/components"] and vite.config.ts defines '@': path.resolve(__dirname, './src'), the two configurations use different alias granularities. For simple import paths these may coincidentally produce the same result, but when the alias definitions genuinely diverge — because one was updated and the other was not — TypeScript accepts imports that the bundler rejects at build time, or vice versa. This mistake is subtle because it surfaces only after a configuration change, not when the project is first set up. Adding a CI step that validates the consistency of alias definitions across both configs — or better, generating both from a single source of truth — prevents this class of mismatch from reaching production.

  • FEE-1700 — TypeScript Overview
  • FEE-1705 — Declaration Files & DefinitelyTyped
  • FEE-800 — Build Tooling Overview

References ​