Sub topic 16
Catching errors before they merge
This chapter assumes you can already run tsc, read a diagnostic, and fix the common families (TS2322, TS2345, TS2741, TS18048). It covers the last step: making sure a type error is caught automatically before it reaches your main branch. You need Node.js, npm, and a project with a tsconfig.json.
Why a local check is not enough
Your editor shows type errors as you type. That helps, but it does not enforce anything. A teammate may use a different editor, ignore a red underline, or commit from a machine where the dependencies are out of date. A CI check is the only place where every change is verified the same way.
Many build tools never check types. Babel, esbuild, swc, and Vite's dev server strip the type annotations and emit JavaScript without reporting type errors. A project can build and run while tsc would report dozens of errors. For that reason the type check has to be its own step. Don't rely on the build to do it.
A dedicated type-check script
The simplest check is tsc --noEmit. The compiler reports diagnostics and writes no files. If there is at least one error, it exits with a non-zero status, and that status is what makes a CI job fail.
{
"name": "my-app",
"private": true,
"scripts": {
"typecheck": "tsc --noEmit",
"lint": "eslint .",
"test": "node --test",
"check": "npm run typecheck && npm run lint && npm test"
},
"devDependencies": {
"eslint": "^9.0.0",
"typescript": "5.6.3",
"typescript-eslint": "^8.0.0"
}
}Put the check behind a named script so that developers and CI run the same command. Two details matter here:
- Pin the TypeScript version. Each minor release can add or tighten checks. With a range like
^5.6.0, a fresh install in CI may use a newer compiler than the one on your laptop, and the build can break with no code change. Pin the exact version and upgrade it on purpose, in its own pull request. - Commit the lockfile and install with
npm ci. This installs exactly what the lockfile lists.npm installmay update it.
Running the check in CI
This GitHub Actions workflow runs the check on every pull request and on pushes to main.
name: ci
on:
pull_request:
push:
branches: [main]
jobs:
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run typecheckThe same structure works in other CI systems. Check out the code, install with the lockfile, run the script, and fail the job on a non-zero exit code. Then mark the job as a required status check in your repository's branch protection settings. Without that step the check only advises. Someone can still merge a red pull request.
Making the check fast
On a large project, a full check can take a minute or more. Three options help:
- Incremental mode. With
"incremental": true, the compiler saves information about the previous run in a.tsbuildinfofile and re-checks only what changed. This works together withnoEmit. In CI it only helps if you cache that file between runs. skipLibCheck. Setting"skipLibCheck": trueskips checking.d.tsfiles, including those innode_modules. It speeds up the check and hides errors caused by conflicting declaration files in your dependencies. It does not hide errors in your own code. Most projects enable it.- Project references. In a monorepo, split the code into packages with their own
tsconfig.jsonand usetsc -b(build mode). Each package is checked once and only rebuilt when its inputs change.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"incremental": true,
"tsBuildInfoFile": "./.cache/tsconfig.tsbuildinfo"
},
"include": ["src"]
}Add .cache/ to .gitignore. The build info file is a cache, not source.
Checking before the commit
A CI run takes minutes to report a mistake that a pre-commit hook can catch in seconds. Tools such as Husky or lefthook can run npm run typecheck before each commit. There is one caveat. tsc checks the whole project, not just the staged files. Passing individual file names to tsc makes it ignore tsconfig.json, which changes the options and usually produces wrong results. Run it on the whole project, or leave the type check to CI and keep the hook for fast checks like formatting.
Treat hooks as a convenience. Developers can bypass them with git commit --no-verify, so CI remains the real gate.
Keeping suppressions honest
The escape hatches from the previous chapters are also a way for errors to slip through review. Two controls keep them visible:
- Use
@ts-expect-error, not@ts-ignore. When the code is fixed later and the line stops failing, the compiler reports an unused directive, so a stale suppression cannot stay in place unnoticed. - Require a reason with each one. The
@typescript-eslint/ban-ts-commentrule can do this.
// eslint.config.mjs
import tseslint from "typescript-eslint";
export default tseslint.config(
...tseslint.configs.recommended,
{
rules: {
"@typescript-eslint/ban-ts-comment": [
"error",
{
"ts-expect-error": "allow-with-description",
"ts-ignore": true,
"ts-nocheck": true,
minimumDescriptionLength: 10,
},
],
},
},
);With this setting, a bare // @ts-expect-error fails the lint step, while // @ts-expect-error: legacy API returns string, see issue 482 passes. Reviewers can then see why the check was bypassed.
Adopting strict checks in an existing project
Turning on "strict": true in a large codebase can produce hundreds of errors at once. You can't merge that, and a check that is always red gets ignored. These approaches add strictness in steps:
- One flag at a time. Start with
noImplicitAny, fix its errors, then addstrictNullChecks, and so on. Each step is a small pull request. - A second config for migrated code. Create a stricter configuration that covers only the directories you have already cleaned, and run both checks in CI.
{
"extends": "./tsconfig.json",
"compilerOptions": { "strict": true },
"include": ["src/billing", "src/auth"]
}Run it with tsc -p tsconfig.strict.json --noEmit. There is a gotcha. A file in src/billing that imports from an unmigrated directory pulls that file into the program, and the compiler checks it under strict rules too. You may need to migrate in dependency order, starting with files that import little.
Another option is a baseline. Record the current error count and fail CI only if it goes up. This stops regressions, but it is a weaker guarantee than a clean check, since a new error can hide behind a fixed one. Use it as a temporary measure with a plan to reach zero.
Common failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| CI fails but `tsc` passes locally | Different TypeScript version, or stale `node_modules` | Pin the version, run `npm ci` locally |
| CI is green but types are wrong at runtime | The job runs the build, not `tsc` | Add a `typecheck` step |
| Check passes on a file you expect to fail | The file is not matched by `include` | Check `include`, or run `tsc --listFiles` |
| Errors appear only in CI after a dependency update | Lockfile not committed, or a version range | Commit the lockfile, use `npm ci` |
| Test files never type-checked | Tests live outside `include` | Include them, or add a second tsconfig for tests |
Exercise
Your team's build uses esbuild and passes on every pull request, yet a type error reached production. What two changes would you make to stop this from recurring, and why does the first one work?
Show answer
First, add a separate CI step that runs tsc --noEmit (for example as an npm script called typecheck), because esbuild removes type annotations without checking them, so a passing build says nothing about type correctness. Second, mark that job as a required status check in branch protection so a failing type check blocks the merge. Pinning the TypeScript version and installing with npm ci keeps the result the same on every machine.
Exercise
A pull request adds // @ts-expect-error with no explanation above a failing call. Which lint rule can reject it, and what option value permits the comment only when it has a description?
Show answer
The @typescript-eslint/ban-ts-comment rule, with "ts-expect-error": "allow-with-description". Setting minimumDescriptionLength makes very short descriptions fail too. Banning ts-ignore in the same rule means a suppression that has gone stale is reported by the compiler instead of staying hidden.