Skip to content
FEE
Frontend Engineering Essentials
Mid Level

TypeScript Configuration ​

A tsconfig.json file is the contract between your source code and the TypeScript compiler. It determines which type errors the compiler will catch, what syntax the output targets, how modules resolve, and whether the build is incremental. Every team has one — most teams treat it as boilerplate, copied from a project starter and rarely revisited.

That default approach leaves type safety on the table. The strict flag is not enabled by default in TypeScript. noUncheckedIndexedAccess, which prevents silent undefined reads from arrays and index signatures, is not part of strict. verbatimModuleSyntax, which prevents import/export mismatches that cause runtime failures in transpile-only pipelines, is disabled by default. These gaps are not obscure edge cases — they are whole categories of bugs that the compiler could catch and is not.

The modern TypeScript ecosystem has also introduced configuration options that did not exist two years ago: moduleResolution: "Bundler" (TypeScript 5.0) correctly models how Vite, esbuild, and other bundlers resolve modules, replacing the legacy "node" setting that still appears in most project starters. verbatimModuleSyntax replaced the older importsNotUsedAsValues and preserveValueImports flags, consolidating type-import discipline into a single, clearer option.

Configuration is not a one-time setup task. It is a living document that must be updated as the TypeScript compiler adds new checks, as the module system evolves, and as the project's build pipeline changes. A tsconfig.json that was correct in 2022 may silently miss errors in 2024.

Design Thinking ​

The strict umbrella and why partial flags are not equivalent ​

TypeScript's --strict flag is a shorthand for enabling a set of individual strictness flags: strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitAny, noImplicitThis, alwaysStrict, and useUnknownInCatchVariables. Developers who disable strict and manually enable only strictNullChecks believe they have replicated the important parts of strict mode — they have not.

The individual flags miss two things. First, strict is forward-compatible: when TypeScript adds new strictness flags in future releases, they are automatically included under strict: true. A project that manually lists individual flags will silently not receive new checks. Second, strict includes interactions between flags that are not individually re-creatable. The correct approach is always to start with strict: true and add additional flags on top — never to assemble an ad-hoc collection of individual strictness options.

The migration path for projects that cannot immediately fix all strict errors is // @ts-ignore on specific lines or @ts-expect-error with explanations, not disabling strict globally. A project with strict: true and 20 suppressed errors is in a much better position than a project with strict: false — the 20 suppressions are visible, tracked, and can be resolved incrementally.

target vs. lib vs. module: a common misconception ​

Three tsconfig.json fields control output, and they are commonly confused:

  • target — the JavaScript syntax version that TypeScript emits. "ES2022" means TypeScript will emit ES2022 syntax (arrow functions, optional chaining, etc. are left as-is; older syntax is downleveled). It does NOT mean you have access to ES2022 APIs.
  • lib — the type definitions included for the runtime environment. "ES2022" in lib means TypeScript knows about Array.prototype.at(), Object.hasOwn(), and other ES2022 APIs. Without the matching lib entry, TypeScript will report these as unknown.
  • module — the module format of the emitted JavaScript. "ESNext" emits ES module syntax (import/export). "CommonJS" emits require()/module.exports.

A project with target: "ES2022" but no lib: ["ES2022"] will see errors when using Array.prototype.at() even though the runtime supports it. A project with lib: ["ES2022"] but target: "ES5" will have type-safe access to Array.prototype.at() but emit code that calls it in an ES5 bundle — a runtime error if the polyfill is absent.

In practice: for browser apps with a modern bundler, set target: "ES2022", lib: ["ES2022", "DOM", "DOM.Iterable"], and module: "ESNext". Let the bundler handle transpilation to the actual browser targets via its own configuration (e.g., Vite's build.target or Babel's @babel/preset-env).

Path aliases: type-checking layer vs. runtime resolution ​

TypeScript's paths field maps import aliases to file paths at type-checking time. When the compiler sees import { Button } from '@/components/Button', it looks up @/* in paths, resolves it to ['src/*'], and finds src/components/Button.ts. The import type-checks correctly.

None of this affects the emitted JavaScript. The compiled output still contains import { Button } from '@/components/Button' — a bare specifier that Node.js or the browser does not know how to resolve. The bundler must also be configured to resolve the same alias.

This two-layer architecture is frequently the source of an insidious class of bugs: the TypeScript compiler passes, CI passes, the app fails at runtime or bundle time with a "Cannot find module '@/components/Button'" error. The fix is to always configure aliases in both places — and to use vite-tsconfig-paths in Vite projects, which reads tsconfig.json paths automatically and applies them to Vite's module resolution, eliminating the duplication.

verbatimModuleSyntax and transpile-only pipelines ​

TypeScript's traditional compilation model runs full type checking before emit. Transpile-only tools (esbuild, SWC, Babel, Vite's transform pipeline) do not — they strip type annotations mechanically, file by file, without a full program analysis. This creates a specific failure mode with type imports.

Consider:

typescript
import { UserRole } from './types'

const check = (role: UserRole) => role === 'admin'

If UserRole is a type (not a value), the traditional TypeScript compiler removes the import during type erasure. A transpile-only tool that strips types file-by-file may or may not remove this import, depending on its implementation — it may emit import { UserRole } from './types' into the JavaScript output, creating a runtime import of a symbol that does not exist as a value.

verbatimModuleSyntax solves this by requiring explicit import type syntax for type-only imports. The compiler error is immediate and visible: "This import is never used as a value and must use 'import type' because 'verbatimModuleSyntax' is specified." Developers learn the distinction, write import type { UserRole } from './types', and the transpile-only tool has an unambiguous signal to strip the import.

Best Practices ​

MUST enable strict: true and three additional strictness flags: noUncheckedIndexedAccess, exactOptionalPropertyTypes, and noImplicitOverride. These three flags are not included in the strict umbrella but catch significant error categories. noUncheckedIndexedAccess adds | undefined to all array index accesses and index signature lookups, forcing explicit null-guards. exactOptionalPropertyTypes distinguishes between a property being set to undefined and a property being absent, preventing a class of assignment errors. noImplicitOverride requires the override keyword on methods that shadow a base class method, preventing silent failures when the base class method is renamed.

MUST enable verbatimModuleSyntax: true in any project using a transpile-only build tool. This flag requires that type-only imports use import type and type-only re-exports use export type, giving transpilers an unambiguous signal to strip type imports without executing module side effects. Teams migrating from the older importsNotUsedAsValues: "error" setting MUST know that verbatimModuleSyntax is a superset and also enforces export type for type-only re-exports; the migration is mechanical — run tsc, fix the reported errors, and commit.

MUST use vite-tsconfig-paths to sync path aliases between tsconfig.json and Vite rather than duplicating them manually. Manual alias duplication in resolve.alias creates a synchronization hazard: adding an alias to tsconfig.json without updating vite.config.ts produces a type-check success and a runtime failure. The vite-tsconfig-paths plugin reads aliases directly from tsconfig.json, eliminating this entire class of error.

MUST structure TypeScript configuration in three layers: tsconfig.base.json, tsconfig.json, and tsconfig.test.json. The base file defines strictness, compiler behavior, and module system settings without include or exclude entries, and is shared across all packages in a monorepo. The application config extends base and adds baseUrl, paths, and include for application source. The test config MUST extend base, not the application config, and adds test-framework types and test file patterns in isolation from application paths.

SHOULD use project references with composite: true and declarationMap: true in monorepos with multiple TypeScript packages. Project references allow tsc --build to use the project graph to rebuild only changed packages and their dependents, and to surface type errors in library packages when building consumer applications. declarationMap: true enables go-to-definition to navigate to source files rather than .d.ts declarations, which is essential for developer experience when packages are developed alongside the consuming application.

Visual ​

tsconfig Inheritance Chain ​

The following diagram shows how the three-layer tsconfig inheritance chain is structured and what each layer contributes.

Example ​

Complete tsconfig Setup ​

This example shows a complete, production-ready tsconfig setup for a Vite + Vitest application.

json
// tsconfig.base.json
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "verbatimModuleSyntax": true,

    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "Bundler",

    "skipLibCheck": true,
    "noEmit": true,
    "resolveJsonModule": true,
    // isolatedModules omitted: verbatimModuleSyntax is a strict superset; deprecated in TS 5.5+

    "jsx": "react-jsx"
  }
}

Note: moduleResolution: "Bundler" was introduced in TypeScript 5.0. It correctly models the module resolution algorithm used by Vite, esbuild, and other bundlers — they support index files, extension omission, and exports field in package.json in a way that the legacy "node" setting does not model accurately.

json
// tsconfig.json  (application config, used by editor and tsc)
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"],
      "@lib/*": ["src/lib/*"]
    }
  },
  "include": ["src/**/*", "vite.config.ts"]
}
typescript
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  plugins: [
    react(),
    tsconfigPaths(), // reads paths from tsconfig.json automatically
  ],
  build: {
    target: 'es2022',
  },
})
json
// tsconfig.test.json  (test config, used by Vitest)
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "types": ["vitest/globals"]
  },
  "include": [
    "src/**/*.test.ts",
    "src/**/*.test.tsx",
    "src/**/*.spec.ts",
    "src/**/*.spec.tsx"
  ]
}

Configure Vitest with vite-tsconfig-paths so path aliases from tsconfig.json are resolved during tests. Vitest discovers the nearest tsconfig.json automatically — no tsconfig key is needed in the config:

typescript
// vitest.config.ts
import { defineConfig } from "vitest/config";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [tsconfigPaths()],
  test: {
    globals: true,
    environment: "jsdom",
  },
});

Using the Configuration in Code ​

With noUncheckedIndexedAccess enabled, array index access now returns T | undefined:

typescript
// src/lib/users.ts
import type { User } from '@/types'  // verbatimModuleSyntax requires import type

const users: User[] = fetchUsers()

// TypeScript error without undefined guard:
// const name = users[0].name  — Object is possibly 'undefined'

const first = users[0]
if (first !== undefined) {
  console.log(first.name)  // safe: first is User here
}

// Or use optional chaining:
const name = users[0]?.name  // string | undefined

With exactOptionalPropertyTypes, optional property assignment is stricter:

typescript
interface Config {
  timeout?: number  // can be absent, but not explicitly undefined
}

// Error with exactOptionalPropertyTypes:
// const cfg: Config = { timeout: undefined }

// Correct:
const cfg1: Config = {}             // property absent — OK
const cfg2: Config = { timeout: 5000 }  // property present — OK

// If you need to allow explicit undefined:
interface Config2 {
  timeout?: number | undefined      // explicitly allows undefined assignment
}

Common Mistakes ​

ts-node without esm: true ​

Running TypeScript files directly with ts-node in a project configured with "module": "ESNext" causes a SyntaxError: Cannot use import statement in a module at runtime, even though tsc reports no errors. The fix is to add ts-node configuration to tsconfig.json:

json
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Bundler"
  },
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  }
}

Note: experimentalSpecifierResolution was removed in Node.js 21. On Node.js 21+, prefer tsx (shown below) or set "type": "module" in package.json instead.

Alternatively, use tsx (a ts-node replacement using esbuild) which handles ESM projects without configuration.

  • FEE-1600 — Developer Experience & Tooling Overview — Category context: TypeScript configuration is the foundation of the type-safety layer in the DX lifecycle
  • FEE-1601 — Linting & Static Analysis — Type-aware ESLint rules (@typescript-eslint/recommended-type-checked) require a tsconfig.json with project path configured; strict tsconfig produces more accurate lint results
  • FEE-803 — Transpilation — esbuild, SWC, and Babel are transpile-only tools that strip TypeScript without type checking; verbatimModuleSyntax and isolatedModules are the tsconfig flags that align TypeScript's model with transpiler behavior
  • FEE-805 — Monorepo Tooling — Project references with composite: true are the TypeScript-native approach to incremental builds and cross-package type checking in monorepos

References ​