Sub topic 16
Keep it typed: linting, tests and CI
This chapter assumes you have already converted at least one file, that tsc runs cleanly on it, and that you can read basic npm scripts. It also assumes you have used Git and a hosted CI service. Here you will add checks that stop the converted code from drifting back to untyped habits.
Why a passing compile is not enough
After a conversion, the code type-checks on your machine once. Nothing keeps it that way. A teammate can add any to silence an error, add a // @ts-ignore, or merge a change that nobody type-checked. The checks in this chapter keep the compiler's guarantees in place.
You need four checks, and each catches something the others miss:
| Check | Tool | What it catches |
|---|---|---|
| Type check | `tsc --noEmit` | Type errors across the whole project |
| Lint | ESLint with typescript-eslint | Risky patterns that type-check, such as unhandled promises and explicit `any` |
| Tests | Vitest | Wrong runtime behavior |
| Build | `tsc` with a build config | Output that fails to emit or run |
Separate type checking from building
During migration, tsc does two jobs: it checks types and it writes JavaScript. Split them. tsc --noEmit checks every file without writing output, so it is fast and safe to run anywhere.
Test files are the complication. You want them type-checked, but you do not want them in dist. Add a second config that extends the first and leaves them out.
{
"extends": "./tsconfig.json",
"exclude": ["src/**/*.test.ts"]
}Save this as tsconfig.build.json. The type check uses tsconfig.json, which includes tests. The build uses tsconfig.build.json, which does not.
Lint with typescript-eslint
The compiler reports type errors. A linter reports code that is legal but suspicious. Install ESLint and the TypeScript plugin:
npm install --save-dev eslint @eslint/js typescript-eslintThen create eslint.config.mjs in the project root:
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
export default [
{ ignores: ["dist/**"] },
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
files: ["**/*.mjs"],
...tseslint.configs.disableTypeChecked,
},
];The recommendedTypeChecked set reads your tsconfig.json, so its rules can use real type information. The last block turns type-aware rules off for the config file itself, which is not part of the TypeScript project. import.meta.dirname needs Node 20.11 or later.
Rules in this set that matter most during a migration:
@typescript-eslint/no-explicit-anyrejectsanythat you wrote by hand.@typescript-eslint/no-unsafe-assignment,no-unsafe-member-accessandno-unsafe-callflag values that arrive asany, for example fromJSON.parseor an untyped library.@typescript-eslint/no-floating-promisesflags an async call whose result is never awaited or handled.@typescript-eslint/ban-ts-commentrejects// @ts-ignore. It allows// @ts-expect-erroronly with a description.
Prefer @ts-expect-error over @ts-ignore when you must suppress an error. It fails the build once the error disappears, so stale suppressions cannot linger.
On a large file, the no-unsafe-* rules can produce hundreds of findings at first. Downgrade them to warnings, then raise them to errors as you clear the backlog:
{
rules: {
"@typescript-eslint/no-unsafe-assignment": "warn",
"@typescript-eslint/no-unsafe-member-access": "warn",
"@typescript-eslint/no-unsafe-call": "warn",
},
},Add this object to the config array after recommendedTypeChecked. Later entries override earlier ones.
Write tests that the compiler also checks
Vitest runs TypeScript with no extra setup:
npm install --save-dev vitestExport the function from the earlier chapters so a test can import it. This is src/formatUser.ts:
export interface User {
name: string;
age: number;
email?: string;
}
export function formatUser(user: User): string {
return user.name.toUpperCase() + " (" + user.age + ")";
}Then write src/formatUser.test.ts:
import { describe, expect, it } from "vitest";
import { formatUser } from "./formatUser";
describe("formatUser", () => {
it("upper-cases the name and appends the age", () => {
expect(formatUser({ name: "Ada", age: 36 })).toBe("ADA (36)");
});
it("rejects a user without an age at compile time", () => {
// @ts-expect-error age is required by the User interface
formatUser({ name: "Ada" });
});
});The second test checks the types rather than the runtime result. If someone makes age optional, the @ts-expect-error line no longer has an error, and tsc --noEmit fails. The call itself does not throw at runtime, so the test passes in Vitest either way. Only the compiler enforces the contract.
Put it all in npm scripts
Give every check a name in package.json, so developers and CI run the same commands:
{
"scripts": {
"typecheck": "tsc --noEmit",
"lint": "eslint .",
"test": "vitest run",
"build": "tsc -p tsconfig.build.json",
"check": "npm run typecheck && npm run lint && npm run test"
}
}vitest run runs once and exits. Plain vitest starts watch mode and would hang a CI job. The && operator stops at the first failing step, so npm run check reports the earliest problem.
Run the checks in CI
This GitHub Actions workflow runs the same scripts on every push and pull request. Save it as .github/workflows/ci.yml:
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
check:
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 check
- run: npm run buildUse npm ci, not npm install. It installs exactly what package-lock.json lists and fails if the lockfile is out of date. This pins the TypeScript version, so a new compiler release cannot break your build overnight. Upgrade TypeScript on purpose, in its own pull request.
Then mark the check job as required in your repository's branch protection settings. A check that people can merge past will not hold up for long.
Ratchet strictness without blocking the team
The previous chapter enabled strict flags in stages. CI can enforce each stage as it lands. One option is to turn on the flag globally once all errors are fixed. If that is not possible yet, a second config can apply the stricter settings to files you have finished:
{
"extends": "./tsconfig.json",
"compilerOptions": { "strict": true, "noEmit": true },
"include": ["src/formatUser.ts", "src/config.ts"]
}Save this as tsconfig.strict.json and add the script "typecheck:strict": "tsc -p tsconfig.strict.json". Add each file you finish to include. Files in the list can never regress, and the rest of the project can keep moving. When the list covers everything, delete this file and set "strict": true in the main config.
Note that a file listed here is still checked along with the files it imports, so a strict file that imports a loose one will report errors from the loose one's types where they flow into it.
Common problems
- Editor and CI disagree. The editor may use a different TypeScript version. Select the workspace version, which is the one in
node_modules. skipLibCheckhides real problems. It skips checking of.d.tsfiles, including your own. It is fine for speed, but a broken declaration file in your own code will not be reported.- Lint errors on the config file. If ESLint says a file is not found by the project service, the file is outside
includeintsconfig.json. Either disable type-aware rules for it, as shown above, or add it to the project. - Tests compiled into
dist. The build is usingtsconfig.jsoninstead oftsconfig.build.json. Check the-pflag.
Exercise
A pull request passes npm test but fails npm run typecheck with "Object is possibly 'undefined'". Why can the tests pass, and which step should block the merge?
Show answer
Vitest strips types without checking them, so a type error does not stop tests from running. Both steps must be required. The typecheck failure blocks the merge, because the code can crash at runtime for inputs the tests do not cover.
Exercise
Why is // @ts-expect-error safer than // @ts-ignore when you need to suppress a known error during migration?
Show answer
@ts-expect-error itself becomes an error when the line it covers no longer has a type error. A stale suppression is reported and can be removed. @ts-ignore stays silently, even after the underlying problem is fixed, and can hide new errors later.
Exercise
Write the npm script that runs the Vitest suite once and exits, suitable for CI, and say why vitest alone is a poor choice.
Show answer
"test": "vitest run". Plain vitest starts watch mode, which waits for file changes and never exits, so a CI job would hang until it times out.