Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 96 ยท TypeScript in Practice

Tooling: Linting, Testing and Building

Set up a professional TypeScript toolchain - ESLint with typescript-eslint, Prettier, Vitest and type tests, CI type checks, and building apps and libraries.

The TypeScript compiler answers one question very well: "do these types fit together?" A real project needs more answers than that. Is this code formatted consistently? Did someone forget to await a promise? Does the function return the right value, not just the right type? How do the .ts files become something a browser or an npm user can load?

Each of those questions has its own tool. This lesson walks through the standard toolbox: ESLint with typescript-eslint for bug patterns the compiler allows, Prettier for formatting, Vitest (or Jest, or Node's built-in runner) for tests, type tests for code whose whole job is its types, and the build tools that turn TypeScript into JavaScript for apps and libraries. Our editor has no npm, so configuration files appear as read-only code, while the runnable examples show the ideas each tool is built on.

The toolbox at a glance

Job Typical tool What it catches or produces
Type checking tsc --noEmit Type errors across the whole project
Linting ESLint + typescript-eslint Bug patterns that are type-correct (floating promises, unsafe any, unreachable branches)
Formatting Prettier Consistent layout; no style debates in code review
Unit tests Vitest, Jest, node:test Wrong values and behavior at runtime
Type tests expectTypeOf, Expect<Equal<โ€ฆ>> Wrong types in libraries and utility types
Building Vite, esbuild, tsdown, tsc JavaScript bundles, .d.ts declaration files

A useful rule of thumb: the compiler checks types, the linter checks habits, tests check behavior. None of them replaces the others.

Linting with ESLint and typescript-eslint

ESLint is the standard JavaScript linter. On its own it can't read TypeScript syntax, so the typescript-eslint project adds a parser and a set of TypeScript-aware rules. Installing them is one command:

Terminal
npm install --save-dev eslint @eslint/js typescript-eslint

Modern ESLint uses a "flat" config file, eslint.config.mjs, at the project root:

JavaScript
// eslint.config.mjs
import eslint from '@eslint/js';
import { defineConfig } from 'eslint/config';
import tseslint from 'typescript-eslint';

export default defineConfig(
  eslint.configs.recommended,
  tseslint.configs.recommendedTypeChecked,
  {
    languageOptions: {
      parserOptions: {
        projectService: true, // use the nearest tsconfig.json for type information
        tsconfigRootDir: import.meta.dirname,
      },
    },
    rules: {
      '@typescript-eslint/switch-exhaustiveness-check': 'error',
      '@typescript-eslint/consistent-type-imports': 'error',
    },
  },
);

Run it with npx eslint .. The important word in that config is TypeChecked. Plain recommended rules only look at syntax. The type-checked presets ask the TypeScript compiler about the type of every expression, which unlocks the most valuable rules:

  • no-floating-promises: a promise was created and nobody awaited it, returned it or handled its rejection.
  • no-misused-promises: an async function was passed where a plain callback is expected (for example to forEach or an if condition).
  • no-unsafe-assignment, no-unsafe-call, no-unsafe-member-access: an any value is leaking into typed code (see any, unknown, never and void).
  • no-unnecessary-condition: a check that can never be false according to the types, which usually means the types or the logic are wrong.
  • switch-exhaustiveness-check: a switch over a union misses a case (the linter version of the never trick from Discriminated Unions).

A bug the compiler happily accepts

Here is the classic case for a linter. The code below type-checks perfectly, because calling an async function without await is legal JavaScript. It still does the wrong thing:

TypeScript A floating promise compiles fine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

In the buggy version, "checkout finished" prints before "saved order 1": the confirmation email would go out before the order exists, and if saveOrder threw, nobody would catch the error. no-floating-promises flags line 7 with a message that the promise must be awaited, returned, or explicitly ignored with the void operator (void saveOrder(1); says "I know, and I don't care about the result").

Type-aware linting is slower than syntax-only linting because it builds a full TypeScript program. It's worth it for the rules above. In big monorepos, run the type-checked rules in CI and on changed files, and keep editor linting fast. typescript-eslint talks to the compiler through its JavaScript API, so when you move a project to the native TypeScript 7 compiler, check which TypeScript versions your typescript-eslint release supports. During the transition, many teams keep the 6.0 typescript package installed for tools that need that API and use TypeScript 7 for fast type checking.

Formatting with Prettier

Prettier reformats code to one consistent style: indentation, quotes, line breaks, trailing commas. It doesn't look for bugs, which is exactly why teams like it: formatting stops being a topic in code review. A small .prettierrc covers most preferences:

JSON
{
  "singleQuote": true,
  "semi": true,
  "trailingComma": "all",
  "printWidth": 100
}

Run npx prettier --write . to format everything, or npx prettier --check . in CI to fail on unformatted files. Most editors format on save. Let Prettier own layout and ESLint own correctness: the official ESLint presets no longer include formatting rules, and if you add other shared configs, eslint-config-prettier turns off any rules that would fight with Prettier.

Testing TypeScript code

Tests check what types can't: that formatPrice(1999) really returns '$19.99'. All modern test runners can load .ts files directly.

  • Vitest is the usual choice for new projects. It reads TypeScript through Vite's built-in transformer (esbuild, or Oxc since Vite 8), so tests start instantly, and its API (describe, it, expect) matches Jest's.
  • Jest is still everywhere in older codebases. It needs a transformer: ts-jest (type checks while testing, slower) or Babel/SWC (strips types, fast).
  • node:test is built into Node. Since Node can strip types itself, node --test runs *.test.ts files with no dependencies at all.

A Vitest test file looks like this:

TypeScript
// src/price.test.ts
import { describe, expect, it } from 'vitest';
import { formatPrice } from './price.js';

describe('formatPrice', () => {
  it('formats cents as dollars', () => {
    expect(formatPrice(1999)).toBe('$19.99');
  });

  it('rejects negative amounts', () => {
    expect(() => formatPrice(-1)).toThrow(RangeError);
  });
});

Vitest, Jest with Babel/SWC and node --test all strip types without checking them. A test file with a type error still runs. Always run tsc --noEmit as a separate step (locally and in CI) so type errors can't hide behind green tests.

What a test runner actually does

There's no magic inside a test runner. It collects named functions, runs each one, and reports which threw an error. Building a tiny one is the best way to understand the real tools, and it runs in our editor:

TypeScript A mini test runner with node:assert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Four tests pass and the last one fails with Not a price: $1,250.00: the regular expression doesn't allow commas. That's a test doing its job, finding a case the author didn't think about. Try fixing the pattern (for example /^\$([\d,]+)\.(\d{2})$/ plus removing the commas before Number(...)) and run again.

Notice what the types did here: TestFn allows both sync and async tests, and catch (error) gives you unknown (see Error Handling), so the runner has to check error instanceof Error before it reads .message.

Node's built-in runner

The same ideas ship with Node as node:test. It works in our editor too, so you can see real runner output:

TypeScript Tests with node:test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The runner prints a tree of passing tests (โœ”) and a summary with counts. The durations change on every run. In a real project you would put this in cart.test.ts and run node --test, which finds test files by name.

Testing types

Some code exists only for its types: a utility type like DeepReadonly<T>, a typed event emitter, an API client whose return type depends on the endpoint. A runtime test can't tell you that get('/users') returns Promise<User[]> and not Promise<any>. A type test can.

The simplest type tests need no library. Two small helpers do the work:

TypeScript
type Expect<T extends true> = T;
type Equal<A, B> =
  (<X>() => X extends A ? 1 : 2) extends (<X>() => X extends B ? 1 : 2) ? true : false;

Equal<A, B> is true only when A and B are exactly the same type (the odd-looking generic functions make the comparison strict, so any doesn't equal everything). Expect<T> only accepts true, so a type test that evaluates to false becomes a compile error. You met them in Built-in Utility Types; here they guard a function's signature:

TypeScript Type tests that pass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The two type _โ€ฆ = Expect<โ€ฆ> lines produce no JavaScript, yet they lock in the promise that groupBy keeps the literal key types. If someone later "simplifies" the signature to return Record<string, T[]>, the build breaks:

TypeScript A failing type test (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Nothing runs; the compiler reports main.ts(16,21): error TS2344: Type 'false' does not satisfy the constraint 'true'. That error is the failing test. In larger projects you'll see library versions of the same idea: Vitest's expectTypeOf(byTeam).toEqualTypeOf<โ€ฆ>() (run with vitest --typecheck) and the tsd package. They give nicer messages, but the principle is identical.

Type checking in CI

Put every check behind an npm script so local runs and CI do exactly the same thing:

JSON
{
  "scripts": {
    "typecheck": "tsc --noEmit",
    "lint": "eslint .",
    "format:check": "prettier --check .",
    "test": "vitest run",
    "check": "npm run typecheck && npm run lint && npm run format:check && npm test"
  }
}

tsc --noEmit type-checks the whole project as described by tsconfig.json without writing files. With the native TypeScript 7 compiler this step is roughly ten times faster than it used to be, so there's no reason to skip it, even in pre-commit hooks. For monorepos, project references and tsc --build check each package once and reuse the results.

Building applications

For an application (a website, a server, a CLI), you usually let a fast tool strip the types and use tsc only for checking:

  • Vite (front end) transpiles with esbuild (Oxc since Vite 8) and bundles production builds with Rollup (Rolldown since Vite 8). It never type-checks; run tsc --noEmit alongside it.
  • esbuild bundles a Node or browser entry point in milliseconds: esbuild src/main.ts --bundle --platform=node --outfile=dist/main.js.
  • Node itself runs .ts files directly (Node 22.18+ and 24) by erasing type annotations, as covered in TypeScript with Node.js. That only works for erasable syntax, which is why the erasableSyntaxOnly option exists: it rejects enum, namespace and parameter properties, which need real code generation.

These tools compile one file at a time and can't see other files' types. Turn on isolatedModules (or verbatimModuleSyntax, from Modules) so the compiler warns about code that a per-file transformer would get wrong, such as re-exporting a type without export type.

Building libraries

A library has an extra job: it must ship declaration files (.d.ts) so its users get types. The compiler writes them when declaration is on:

JSON
{
  "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "strict": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "outDir": "dist",
    "rootDir": "src"
  },
  "include": ["src"]
}

Then package.json tells Node and TypeScript where everything lives. The exports map is what modern resolvers read, and the types condition must come first in each entry:

JSON
{
  "name": "@acme/money",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "default": "./dist/index.js"
    }
  },
  "files": ["dist"],
  "scripts": {
    "build": "tsc"
  }
}

Three refinements are common:

  • isolatedDeclarations (TypeScript 5.5+) requires explicit return types on exported functions, so declaration files can be generated per file by fast tools without running the type checker.
  • Bundling library builds with tools such as tsdown or tsup produces one .js and one .d.ts file and can emit both ESM and CommonJS.
  • Checking the result with a tool like "Are the Types Wrong?" (npx @arethetypeswrong/cli) catches broken exports maps before your users do.

Declaration files themselves are covered in Declaration Files (.d.ts).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your Vitest suite passes, but the file has a type error. What happened?

    Vitest (like Babel, SWC, esbuild and node --test) removes type annotations and runs the JavaScript. Type errors are only caught by a separate tsc --noEmit step.
  2. 2. Which tool would report saveOrder(1); inside an async function where saveOrder returns a promise?

    Calling an async function without await is valid TypeScript, so the compiler is silent. The type-aware lint rule no-floating-promises flags promises that are never awaited, returned or handled.
  3. 3. What does type _t = Expect<Equal<string, number>>; do?

    Equal<string, number> is false, and Expect<T extends true> rejects it with TS2344. Type tests fail at compile time and produce no JavaScript.
  4. 4. In a library's package.json exports entry, where should the types condition go?

    Conditions are matched in order, so types must come first or TypeScript may pick the JavaScript file and find no declarations.
  5. 5. Why do teams run Prettier alongside ESLint instead of using ESLint for formatting?

    Prettier is an opinionated formatter with almost no settings, which ends style debates. ESLint is better spent on rules that find real problems.

Summary

  • The compiler checks types, ESLint checks habits and bug patterns, tests check behavior, Prettier owns formatting.
  • Use typescript-eslint's type-checked presets; no-floating-promises, no-misused-promises and the no-unsafe-* rules catch real bugs that compile fine.
  • Vitest, Jest (Babel/SWC), esbuild, Vite and node --test strip types without checking them, so always run tsc --noEmit as its own step.
  • A test runner is just "run named functions and report which ones throw"; node:assert/strict and node:test give you one with no dependencies.
  • Type tests (Expect<Equal<A, B>>, expectTypeOf) fail at compile time and protect the types of libraries and utilities.
  • Apps: a fast bundler strips types, tsc checks. Libraries: declaration: true, an exports map with types first, and optionally isolatedDeclarations.

Next: Scaling TypeScript: Project References and Build Performance.