tsconfig.json: The Inspector's Rulebook

tsconfig.json: The Inspector's Rulebook in TypeScript: A vehicle test station is two things: a bay with a lift and a set of gauges, and a manual.

The Analogy: The Test Station and Its Inspection Manual

A vehicle test station is two things: a bay with a lift and a set of gauges, and a manual. The bay is what people notice, but the manual is what makes the certificate mean anything, because it lists every item to be examined, the method for examining it and the exact criterion for rejection. The tester does not decide whether a tyre is legal. The manual decides, in millimetres, and the tester's job is to measure and to write down what the measurement means. Change the manual and the same tester in the same bay reaches a different verdict about the same car.

The manual is careful about the difference between outcomes. A tyre worn close to the limit is an advisory: it goes on the certificate, it is explained to the owner, and it does not stop the car leaving. A tyre below the limit is a refusal. An item the tester could not reach -- a brake pipe behind an undertray that does not come off -- is recorded as not tested, which is a third thing again, and honest about itself. Stations also carry local instructions on top of the national manual, so a station that keeps failing the same fault may add its own extra check that the manual does not require.

The manual also decides scope, and this is the part people forget. It says which classes of vehicle this station is equipped and authorised to test, and by saying so it says which vehicles must be turned away at the door. A bay that will test anything that rolls in looks generous and busy, and it will eventually issue a certificate for a vehicle it has no gauge for. Being explicit about what is out of scope is not bureaucracy; it is the only way the certificates that are issued can be trusted.

The failure mode is quiet and entirely clerical. A manual binds only if it is the edition in force, and only when somebody opens it. Three things go wrong in practice: the station works from a printed copy that is two amendments out of date, so it fails cars for a criterion that has changed; the station records every marginal fault as an advisory, so nothing ever fails and the certificate stops carrying information; and two testers work from different editions, so the same car passes on Tuesday and fails on Thursday. In all three cases the paperwork looks identical to a correct inspection. That is exactly the problem: a certificate records that a check was performed, not which rules were in force when it was.


Syntax or Core Structure

A TypeScript project's manual is tsconfig.json: a JSON file that may contain comments, sits at the root of the project, and answers three separate questions. Which files are in scope, which JavaScript to emit, and how strictly to check. Running tsc with no file arguments makes it search upward for that file and obey it; tsc --init writes a heavily commented starting version, and a realistic modern one is shorter than what it gives you:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "lib": ["ES2022", "DOM"],
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noUnusedLocals": true,
    "noFallthroughCasesInSwitch": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

Every field in that file is load-bearing. include fixes the scope, so only files under src are ever inspected and nothing in node_modules or dist is visited. target and lib say which JavaScript to emit and which built-in APIs may be assumed to exist. strict is not one rule but a bundle of eight. The three flags underneath it are local instructions that strict deliberately does not include. skipLibCheck stops the compiler checking inside your dependencies' type definitions, which you could not fix anyway.

Point that manual at a small file and it begins refusing things a default tsc would have waved straight through:

// src/rates.ts
const rates: Record<string, number> = { standard: 27, economy7: 19 };

function rateFor(name: string): number {
    return rates[name];
}

console.log(rateFor("standard"));
console.log(rateFor("nonsense"));

Output (tsc 5.4; the file, line and column prefix on each message is trimmed here):

error TS2322: Type 'number | undefined' is not assignable to type 'number'.

That is noUncheckedIndexedAccess earning its keep. Looking a key up in a Record can fail, so the result is number or undefined, and a declared return type of number is a promise the function cannot keep. Delete that one flag and the file compiles, prints 27, and then prints undefined -- a value the signature said was impossible. The honest version has to state what happens when the tariff is not there:

// src/rates.ts
const rates: Record<string, number> = { standard: 27, economy7: 19 };

function rateFor(name: string): number {
    const rate = rates[name];
    if (rate === undefined) {
        throw new Error("no such tariff: " + name);
    }
    return rate;
}

console.log(rateFor("standard"));
try {
    console.log(rateFor("nonsense"));
} catch (err) {
    console.log("caught:", err instanceof Error ? err.message : String(err));
}

Output:

27
caught: no such tariff: nonsense

The catch clause is a second flag showing itself. Under strict, err is unknown rather than any, so reading err.message from it is rejected until you have established that it really is an Error. Both complaints have the same shape -- you assumed a value was there -- and neither was visible in the code the day before the manual changed. Nothing about the source moved; the rules in force did.


Technical Depth: What the Rulebook Actually Says

Almost every argument about TypeScript configuration is really an argument about four things: which rules strict contains, which useful rules it leaves out, where a setting came from, and who is reading the file.

The eight rules bundled into strict

strict: true is shorthand. Writing it switches on the following, and each of them can also be set individually, which is how a migration is done one rule at a time:

FlagWhat it rejectsWhat you notice first
noImplicitAnya parameter or variable whose type cannot be inferredmost of the errors on day one, nearly all in old code
strictNullCheckstreating null and undefined as members of every other typesignatures begin admitting that a lookup can miss
strictFunctionTypesa callback whose parameter types are wider than the position allowsa handler that fitted for years stops fitting
strictBindCallApplycall, apply and bind used with the wrong argument listvery little, unless your code leans on those three
strictPropertyInitializationa class field declared but never definitely assignedconstructors grow assignments or definite-assignment marks
noImplicitThisthis silently becoming any inside a plain functionprototype-era code and callbacks written before arrow functions
useUnknownInCatchVariablesreading a property straight off a caught valueevery catch block in the project at once
alwaysStrictnothing, but it emits a strict-mode directive in every filenothing, until a file was relying on sloppy-mode behaviour

Two things about that list are easy to miss. The first is that it is not fixed forever: releases add members, and 5.6 added one for built-in iterators, so upgrading TypeScript can produce new errors in code that has not been touched. The second is that the flags are independent, so a large legacy project does not have to take all eight at once -- noImplicitAny first and strictNullChecks last is the usual order, because the last one is the one that changes signatures.

The rules strict leaves out

The useful flags outside the bundle are the ones a team adds deliberately, because each of them rejects code that was previously idiomatic:

FlagWhat it addsWhy it is not inside strict
noUncheckedIndexedAccessindexing an array or record yields the value or undefinedit would flag the body of almost every loop ever written
exactOptionalPropertyTypesan absent optional property stops being the same as one set to undefinedit changes how object literals and spreads check
noImplicitReturnsa complaint when some paths return a value and others fall off the endfalling off the end is legal JavaScript and sometimes meant
noFallthroughCasesInSwitcha complaint about a case that runs into the next onefallthrough is occasionally deliberate
noUnusedLocals and noUnusedParameterserrors for bindings nobody readsit makes commenting out one line cascade into errors
verbatimModuleSyntaximports are emitted exactly as written, so type-only imports must say soit only matters for certain bundler and module setups

The switch flags pay for themselves on any code that branches over a union, because the compiler can then prove the branches are exhaustive:

// src/verdict.ts
type Result = "pass" | "advisory" | "fail";

function certificate(r: Result): string {
    switch (r) {
        case "pass":
            return "issued";
        case "advisory":
            return "issued with notes";
        case "fail":
            return "refused";
    }
}

console.log(certificate("pass"), certificate("advisory"), certificate("fail"));

Output:

issued issued with notes refused

There is no default branch and no trailing return, and the file still compiles, because the three cases cover the union exactly. Add "not-tested" to Result and this function -- not the call sites, this function -- reports:

error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

That message comes from strictNullChecks alone, since a function declared to return string may not quietly return undefined. noImplicitReturns extends the same complaint to functions whose return type would have tolerated it. Either way the effect is the one worth having: adding a member to a union produces a list of the places that have to decide what to do about it.

Where a setting came from

A real project rarely has one config file. A base at the repository root holds the shared rules, and each package extends it and overrides only what genuinely differs:

{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "dist",
    "lib": ["ES2022"]
  },
  "include": ["src"]
}

Two inheritance rules govern what that actually means, and both catch people out. An object-valued option such as compilerOptions is merged key by key, so strict from the base survives untouched; an array-valued option is replaced outright, so the lib above discards the base's lib rather than adding to it. Separately, every relative path is resolved against the file it is written in, which means an include of src inside the base file points at a folder next to the base file, not next to the package that extends it. When the result is not obvious, tsc --showConfig prints the fully resolved configuration and ends the argument.

Four fields decide which files exist as far as the compiler is concerned:

FieldMeaning
filesan explicit list of files, with no globbing at all
includeglobs to start from, defaulting to everything beside the config file
excludeglobs removed from what include matched, and nothing more than that
referencesother projects this one depends on, each built and checked separately

The third row is the one that surprises people. exclude filters include; it is not a ban. A file that something in scope imports is pulled into the program and checked regardless, because the compiler cannot check the import without reading what it points at. If a file must genuinely be out of scope, nothing in scope may import it.

The manual is not the workshop

Reading the config is a separate job from building the code, and in a modern project two different tools do them. Vite, esbuild, SWC and tsx all strip type annotations without checking them, which is why they are fast and why a project can ship a type error that never appeared in the terminal. tsc is what checks, and noEmit is how you ask it to check and produce nothing: one command for correctness, another for output. That is also why the same file can be clean in your editor and broken in CI, because the editor may be using its own bundled TypeScript while CI uses the pinned one from the lockfile.


Real World Example: A Day's Results at the Test Station

One day of inspections, printed as the station would print it: a line per vehicle with its advisory count, its verdict and its fee, then the totals and the exceptions. The config in force matters to the code that follows, so it is written at the top of the file where a reader will see it.

// src/inspect.ts
// checked with strict, noUncheckedIndexedAccess and noImplicitReturns
type Outcome = "pass" | "advisory" | "fail";
type Check = { code: string; outcome: Outcome };
type Vehicle = { reg: string; cls: string; mileage: number; checks: Check[] };

const FEE_PENCE: Record<string, number> = { class4: 5485, class7: 5850 };

function c(code: string, outcome: Outcome): Check {
    return { code, outcome };
}

const DAY: Vehicle[] = [
    { reg: "AB12 CDE", cls: "class4", mileage: 84210, checks: [c("tyres", "advisory"), c("brakes", "pass")] },
    { reg: "KL55 MNO", cls: "class7", mileage: 132980, checks: [c("brakes", "fail"), c("lamps", "advisory")] },
    { reg: "XY09 ZZT", cls: "class4", mileage: 45005, checks: [c("tyres", "pass"), c("lamps", "pass")] },
    { reg: "TT77 UUV", cls: "class5", mileage: 9110, checks: [c("lamps", "pass")] },
];

function advisoryCodes(v: Vehicle): string[] {
    return v.checks.filter((k) => k.outcome === "advisory").map((k) => k.code);
}

function verdict(v: Vehicle): string {
    return v.checks.some((k) => k.outcome === "fail") ? "FAIL" : "PASS";
}

function money(pence: number): string {
    return "GBP " + Math.trunc(pence / 100) + "." + String(pence % 100).padStart(2, "0");
}

function pad(text: string, width: number): string {
    return text + " ".repeat(Math.max(0, width - text.length));
}

function report(day: Vehicle[]): string {
    const lines: string[] = [pad("REG", 10) + pad("MILES", 8) + pad("ADV", 5) + pad("RESULT", 9) + "FEE"];
    const notes: string[] = [];
    const unpriced: string[] = [];
    let totalPence = 0;

    for (const v of day) {
        const fee = FEE_PENCE[v.cls];
        let feeText = "fee TBC";
        if (fee === undefined) {
            unpriced.push(v.reg + " (" + v.cls + ")");
        } else {
            totalPence = totalPence + fee;
            feeText = money(fee);
        }
        const codes = advisoryCodes(v);
        for (const code of codes) {
            notes.push(v.reg + " " + code);
        }
        lines.push(pad(v.reg, 10) + pad(String(v.mileage), 8) + pad(String(codes.length), 5)
            + pad(verdict(v), 9) + feeText);
    }

    lines.push(pad("TOTAL", 10) + pad("", 8) + pad("", 5) + pad("", 9) + money(totalPence));
    lines.push("advisory notes: " + notes.join(", "));
    lines.push("unpriced: " + (unpriced.length === 0 ? "none" : unpriced.join(", ")));
    return lines.join("\n");
}

console.log(report(DAY));

Output:

REG       MILES   ADV  RESULT   FEE
AB12 CDE  84210   1    PASS     GBP 54.85
KL55 MNO  132980  1    FAIL     GBP 58.50
XY09 ZZT  45005   0    PASS     GBP 54.85
TT77 UUV  9110    0    PASS     fee TBC
TOTAL                           GBP 168.20
advisory notes: AB12 CDE tyres, KL55 MNO lamps
unpriced: TT77 UUV (class5)

This is a day's work at the station reduced to one table: four vehicles, their mileage, how many advisory notes each collected, whether the certificate is issued, and what the customer owes. Every figure in the FEE column comes out of FEE_PENCE, every verdict comes out of verdict, and the TOTAL line is the running sum of the fees the program was actually able to price. Nothing here is clever. What is worth noticing is which of these lines the rulebook forced into existence.

The single most instructive line is const fee = FEE_PENCE[v.cls];. Without noUncheckedIndexedAccess that expression has type number, the arithmetic below it compiles, and the fourth vehicle contributes NaN to totalPence -- so the TOTAL line reads GBP NaN.NaN and the day's takings are unreportable. With the flag on, fee is number | undefined, totalPence = totalPence + fee is rejected outright, and the only way to make the file compile is to decide what an unknown vehicle class means. The decision the program makes is to record it in unpriced and print fee TBC rather than invent a number. The flag did not write that policy, but it refused to let the file build until a policy existed.

The same discipline shows up in money. The fee never stops being an integer number of pence: Math.trunc(pence / 100) takes the whole pounds, pence % 100 takes the remainder, and only the last step turns either of them into text. padStart(2, "0") is doing real work there -- without it a fee of 5400 prints as GBP 54.0, which is not a price. pad is the other half of the same habit: the column positions in the output are not accidents, they are 10, 8, 5 and 9 added up, which is why FEE begins at character offset 32 on every row including TOTAL.

The limits are real. First, cls is declared string, so "class5" type-checks perfectly and the mistake surfaces as a polite fee TBC in a customer-facing report instead of a compile error; declaring cls: "class4" | "class7" would have moved that failure to the moment someone typed it, and no strictness flag can make that choice for you. Second, FEE_PENCE: Record<string, number> promises a fee for every string in the language, which is precisely the lie noUncheckedIndexedAccess exists to expose -- the flag patches the read site but the type is still wrong. Third, money is only correct for non-negative input: hand it -150 and Math.trunc(-150 / 100) is -1 while -150 % 100 is -50, so it prints GBP -1.-50. Refunds are not hypothetical at a test station, and nothing in tsconfig.json will ever notice that string is malformed, because as far as the compiler is concerned a string was produced and a string was wanted.


Common Mistakes

  1. Treating strict as a single switch: When one file will not compile, the reflex is "strict": false, which switches off eight rules to silence one. Leave strict on and disable the single offender underneath it -- "strict": true with "strictPropertyInitialization": false is a sentence you can defend in review; "strict": false is not.
  2. Putting a top-level field inside compilerOptions: include, exclude, files, extends and references are siblings of compilerOptions, not members of it. Nested in the wrong place they are silently ignored, so your exclude never excludes anything and you conclude the compiler is broken. tsc --showConfig prints what was actually understood.
  3. Believing exclude bans a file: exclude only removes entries from what include swept up. If any compiled file imports the excluded module, it is pulled straight back in and checked. To stop a file being compiled you must stop importing it.
  4. Expecting the bundler to check types: vite build, esbuild, swc and tsx erase annotations without reading them. A green dev server proves the code parsed, not that it type-checks. Run tsc --noEmit in CI or nothing checks your types at all.
  5. Assuming extends merges arrays: Object-valued options such as paths merge key by key, but array-valued ones such as lib, types and include are replaced wholesale by the child. Redeclaring "lib": ["dom"] locally throws away the es2022 the base config gave you.
  6. Forgetting where a relative path is resolved: Paths inside a config are relative to the file they are written in, so a base config in configs/ with "outDir": "./dist" means configs/dist. Extending configs quietly redirect your build output if you do not think about this.
  7. Trusting the editor's TypeScript over the project's: Your editor may run a bundled compiler that is several minor versions ahead of the one in devDependencies. "It is fine on my machine" then means "a different compiler agreed with me". Pin the version in the project and tell the editor to use the workspace copy.
  8. Using skipLibCheck as a blindfold: It is a reasonable default because third-party .d.ts files often disagree with each other, but it also stops checking the declaration files you wrote. If you ship types, build them at least once with skipLibCheck off.
  9. Flipping strict on across a legacy codebase in one commit: Four thousand errors is not a task, it is a wall, and the usual outcome is a spray of // @ts-ignore that hides real defects forever. Enable one flag at a time, or scope the strict config to the directories you have already cleaned.

Best Practices

  • Begin at "strict": true: On a new project it costs nothing, because there is no legacy code to argue with. Every week you delay makes the eventual switch more expensive, and the eight rules it carries are the ones that turn TypeScript from annotation into checking.
  • Add the four flags strict forgot: noUncheckedIndexedAccess, exactOptionalPropertyTypes, noImplicitReturns and noFallthroughCasesInSwitch catch a class of bug the bundle does not. Adopt them one at a time so each error list stays small enough to actually read.
  • Keep one base config and extend it: In a repo with several packages, put shared options in tsconfig.base.json and let each package extend it with only its outDir, rootDir and include. Copied configs drift within weeks, and the drift is invisible until two packages disagree about lib.
  • Run tsc --noEmit as its own CI step: Make it a job that can fail on its own, separate from the bundler build and from tests. A build that emits JavaScript regardless of type errors gives you no signal; a job whose only purpose is checking gives you a red mark on the exact commit that broke it.
  • Pin the compiler exactly: Write "typescript": "5.4.5" with no caret, and set the editor to use the workspace version. New minor releases add rules to strict and sharpen inference, which is good, but you want that change to arrive in a reviewed commit rather than on whichever machine ran npm install last.
  • Fix the type, not the flag: When noUncheckedIndexedAccess complains about a lookup table, the honest repairs are a union key type, a Map with an explicit has check, or a guarded read. Switching the flag off restores the old silence but not the old correctness.
  • Document every disabled rule: A config line that turns something off should carry a comment saying why and, ideally, a ticket number. tsconfig.json permits comments; use them, because the next person cannot tell a deliberate exemption from an accident.
  • Use tsc --showConfig before you argue with the compiler: It prints the fully resolved options and the exact file list after extends, include and exclude have been applied. Most "the flag is not working" reports end the moment someone reads that output.

Practice Exercises

  1. Read the Manual: Run npx tsc --showConfig in a project you already have. Find which of the eight strict rules are on, list any option whose value did not appear in your own tsconfig.json, and name the file it must have come from.
  2. The Missing Fee: Rebuild the FEE_PENCE lookup from the billing program with noUncheckedIndexedAccess on, and get the undefined case to compile in two different ways: once with an if (fee === undefined) guard, and once by typing the key as "class4" | "class7" so an unknown class cannot be passed in at all. Write one sentence on which failure you would rather explain to a customer.
  3. Turn the Flag Off: Set "noUncheckedIndexedAccess": false, run the same program with the guard deleted, and confirm the TOTAL line prints GBP NaN.NaN. Explain in one sentence what the compiler believed about fee that made the arithmetic legal.
  4. Prove the Merge Rules: Write tsconfig.base.json with "lib": ["es2022", "dom"] and "outDir": "./build", then a tsconfig.json in the same folder that extends it and sets only "lib": ["es2022"]. Use --showConfig to show that dom is gone rather than merged, then move the base config into a configs/ subfolder and report where outDir now points.