Skip to content

TypeScript in Node.js: Setup, Types and Tests

Setting up TypeScript in a Node project: understand the tsconfig essentials, type async code and handlers, and get the tests running, step by step from project practice.

≈ 13 min readSoftwareNode.jsBackend

TypeScript is not a Node runtime and not a language that Node executes. It is a check layer in front of it: it kicks in during compilation and is gone without a trace afterward. Everything else follows from this one property – right up to the question that is actually up for debate when you set up a project. That question is not which switch you put into tsconfig.json, but where an error should show up: at your desk, while the cursor is still on the line, or at the user’s end, while the request is already running. TypeScript moves this place of failure forward. The price is a build step and a handful of deliberate configuration decisions; the return is a feedback loop in which seconds, not minutes, lie between “I’m building garbage” and “I can see the garbage.”

Editorial note (July 2026): The main text describes Node 20 and TypeScript 5.4 in March 2024. Current Node versions can run TypeScript with erasable syntax directly. Node strips the types but performs no type checking and ignores tsconfig.json; for TypeScript-specific runtime constructs or a full build, you still need an external tool. For modern Node projects, node16 or nodenext are also the appropriate resolution modes. node10 belongs to the historical CommonJS setup of this article.

The rest is craft, and that is exactly what follows here: a configuration in which every entry has a reason, typed functions and handlers, and finally a test setup that runs .ts files directly.

I assume that Node 20 (the active LTS) is installed and that an npm init has already run. We will build everything else together. If you want to refresh the layer underneath, that is, the Event Loop, the module system and runtime behavior, you will find it in my Node.js training; here we stay one floor up, with types and tools.

What TypeScript actually does in Node#

The decisive point right at the start: Node does not run TypeScript. Node only knows JavaScript. TypeScript is a layer that checks at compile time and then disappears. The types are deleted during compilation; this is called type erasure. At runtime not a single type exists anymore, no interface, no : number. What remains is ordinary JavaScript.

This results in a flow that is the norm in 2024: a .ts file goes through the compiler tsc and becomes a .js file. node runs this .js file. For daily development there is a shortcut: ts-node compiles and starts in one go, without a visible .js file being created. But what ships in the end is always compiled JavaScript.

flowchart LR
  A[source.ts] -->|tsc| B[dist/source.js]
  B -->|node| C[Laufzeit]
  A -.->|ts-node<br/>Entwicklung| C

The dashed branch is the dev convenience; the solid one is what runs in production. Keeping this separation in mind saves a lot of confusion, for example about why a type error stops the build but never shows up in the running program.

One more note: in 2024, Node has no built-in way to start .ts files directly. There is no way around tsc or ts-node; that is the standard. If you read a blog post about “just node index.ts,” you are reading about a future that does not exist yet.

Types as executable contracts#

The change of perspective that has helped me most in projects: a type is not documentation but a contract that a machine enforces on every build. function total(items: LineItem[]): number records two promises, one to every caller and one to me as the author, and the compiler refuses the build as soon as one side breaks its part. The lever lies in the timing: what matters is when correctness is demanded. Without such contracts, the check slips to the back, until a wrong field name or a forgotten undefined only surfaces at the user’s end through an error report. Contracts that kick in earlier report the break while the cursor is still on the line, and they push the length of the feedback loop down to seconds.

This is not free: a compile step, the discipline to maintain types instead of suppressing them with any, and moments in which the compiler insists on something that would never have broken at runtime. The decision therefore falls along a clear edge. The longer a piece of code lives, the more hands touch it and the more expensive a production error is, the more clearly the contract wins. A throwaway script does not need it; a payment path or a public API earns back every one of those seconds.

The foundation: the right packages#

Before we write a single line of configuration, we need three things as a devDependency:

npm install --save-dev typescript @types/node ts-node

typescript provides the compiler. ts-node is the dev tool for starting directly. And @types/node is the package I see forgotten most often in project setups, with noticeable consequences. It contains the type declarations for the Node core APIs: fs, http, events, process, Buffer and all the rest. Without this package, the compiler simply does not know that process exists and reports Cannot find name 'process'. The version follows the Node major version, so for Node 20 the 20.x line.

Rule of thumb: every JavaScript library without its own types needs a matching @types/* package, announced by the message Could not find a declaration file for module 'x'.

tsconfig.json: every switch on purpose#

Now the heart of it. I give a reason for every entry instead of generating the file with a generator and then ignoring it. A baseline for a classic CommonJS Node project:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "CommonJS",
    "moduleResolution": "Node10",
    "strict": true,
    "esModuleInterop": true,
    "outDir": "dist",
    "rootDir": "src",
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "sourceMap": true
  },
  "include": ["src/**/*"]
}

The most important switches and what they actually do:

  • target sets which JavaScript version the code is compiled to. The default is conservative (historically ES3), which produces needlessly old code on a modern Node. ES2022 fits Node 20 and lets async/await, optional chaining and class fields pass through unchanged instead of rewriting them in a roundabout way.
  • module determines the module format of the output. CommonJS is the classic Node way with require. If you want real ESM, you set NodeNext here, but that has consequences.
  • moduleResolution controls how the compiler resolves import paths. The value has no fixed default but depends on module. Node10 goes with CommonJS (formerly written simply as "node"). module: NodeNext goes with moduleResolution: NodeNext. These pairs have to match, or you get resolution errors.
  • strict is the switch that makes TypeScript valuable in the first place. It is false by default, and without it TypeScript is little more than JavaScript with colons. strict: true enables a whole family: noImplicitAny, strictNullChecks, strictFunctionTypes and more. More on that below.
  • esModuleInterop governs imports between CommonJS and ESM. It is also false by default and, as many overlook, is not enabled by strict. You have to set it yourself. Without it, import express from 'express' breaks.
  • outDir determines where the compiled .js files are written. Without it, they land next to the source files, which clutters the project. The convention is dist. Together with rootDir: "src", you get a clean separation: sources live in src, the result in dist.

skipLibCheck skips type checking of the declaration files in node_modules and can speed up the build. It is not risk-free in every project: contradictory or faulty declarations can go unnoticed as a result. resolveJsonModule allows import config from './config.json'. sourceMap generates source maps so that the debugger points to the .ts lines and not to the compiled JavaScript.

Why strict makes the difference#

This becomes clearest in the failure case. Without strict, or more precisely without noImplicitAny, the following passes:

function total(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}

The parameter items has the implicit type any here, and so does item.price. The compiler stays silent, and you have exactly zero type safety; a typo like item.prise only surfaces at runtime. This is the any sprawl: an untyped any spreads, because everything you read from it is any again.

With strict: true, the compiler demands an annotation:

interface LineItem {
  price: number;
  quantity: number;
}

function total(items: LineItem[]): number {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}

Now item.prise is a compile-time error, and the return value is guaranteed to be a number. If a value really does come from outside whose shape you do not know, you reach for unknown instead of any, because unknown forces you to check the type before using it instead of silently undermining it.

Typing async correctly#

Asynchronous code is everywhere in Node, and TypeScript describes it precisely. An async function always returns a Promise<T>; even if the body contains a bare value, it gets wrapped in a promise. Conversely, await unwraps a Promise<T> back to T.

interface User {
  id: number;
  name: string;
  email: string;
}

async function fetchUser(id: number): Promise<User> {
  const response = await fetch(`https://api.example.com/users/${id}`);
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }
  return response.json() as Promise<User>;
}

The return type Promise<User> is the promise to all callers: if you write await fetchUser(1), you get a User, nothing else. Drop the annotation, and an any would creep back in at a place like response.json(), which returns Promise<any> out of the box. An await can also throw an exception; under strict, the catch branch receives it as unknown, which again forces a deliberate type check.

Typing an HTTP handler and an EventEmitter#

Two patterns come up constantly in Node: the HTTP handler and the event-based flow. Both can be typed cleanly as soon as @types/node is installed.

import { createServer, IncomingMessage, ServerResponse } from "node:http";

const server = createServer((req: IncomingMessage, res: ServerResponse): void => {
  if (req.method === "GET" && req.url === "/health") {
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/json");
    res.end(JSON.stringify({ status: "ok" }));
    return;
  }
  res.statusCode = 404;
  res.end("Not Found");
});

server.listen(3000, () => {
  console.log("Server listening on port 3000");
});

IncomingMessage and ServerResponse are the Node types for request and response. Thanks to them, the editor knows that req.method is a string | undefined, and it is exactly this undefined that makes the check req.method === "GET" necessary under strict, not just good style.

The EventEmitter is the second classic. It is dynamic by nature, but you can pin down the event names and their payload with your own interface:

import { EventEmitter } from "node:events";

interface OrderEventMap {
  created: [orderId: string];
  cancelled: [orderId: string, reason: string];
}

class OrderBus extends EventEmitter {
  on<K extends keyof OrderEventMap>(
    event: K,
    listener: (...args: OrderEventMap[K]) => void
  ): this {
    return super.on(event, listener as (...args: unknown[]) => void);
  }

  emit<K extends keyof OrderEventMap>(event: K, ...args: OrderEventMap[K]): boolean {
    return super.emit(event, ...args);
  }
}

const bus = new OrderBus();
bus.on("created", (orderId) => {
  console.log(`Order ${orderId} was created`);
});
bus.emit("created", "order-42");

The gain: bus.emit("created") without the orderId is now a compile error, and in the listener orderId is automatically a string. You have turned the loose event mechanism into a typed contract without changing the Node mechanics. If you want to apply such patterns in the frontend as well, you will find the React side of it in TypeScript in React.

The interop stumbling block: CommonJS and ESM#

In practice, this stumbling block causes the most red squiggles, which is why the warning belongs here. Many npm packages, such as Express, are CommonJS modules with a single module.exports. The intuitive import

import express from "express";

only works when esModuleInterop: true is set. Without this switch, TypeScript insists on the clunky form import * as express from "express", which then often breaks somewhere else at runtime. Internally, the switch inserts the matching interop helpers and thereby allows the natural default import.

The second part of the stumbling block concerns real ESM. If you set "type": "module" in package.json and configure module: "NodeNext", you have to write relative imports with a file extension:

import { total } from "./billing.js";

This is irritating every time: you write .js even though the source file is called billing.ts, because the import describes the state after compilation. If the extension is missing or module and moduleResolution do not match, Node responds with ERR_MODULE_NOT_FOUND. For getting started, I therefore recommend the CommonJS baseline; you take the ESM route deliberately when the project needs it.

Tests that understand TypeScript directly#

That leaves the question of how to run .ts tests without compiling by hand after every change. With Mocha there are two workable ways.

The convenient way for development uses ts-node as a register hook. A .mocharc.json in the project root is enough:

{
  "require": "ts-node/register",
  "extensions": ["ts"],
  "spec": ["test/**/*.spec.ts"]
}

With that, Mocha understands .ts files directly, without a separate build step. A matching test, here with the built-in node:assert:

import assert from "node:assert";
import { total } from "../src/billing";

describe("total", () => {
  it("sums price times quantity", () => {
    const result = total([{ price: 10, quantity: 2 }]);
    assert.strictEqual(result, 20);
  });
});

The second way is the compiled one: first tsc, then run the generated .js tests.

tsc && mocha "dist/**/*.spec.js"

I recommend the ts-node route for the fast development loop and the compiled route for the chain before shipping; there you test exactly the JavaScript that also goes to production. The matching scripts in package.json make this tangible:

{
  "scripts": {
    "dev": "ts-node src/index.ts",
    "build": "tsc",
    "start": "node dist/index.js",
    "test": "mocha"
  }
}

dev starts directly from the source code, build creates the dist directory, start runs the compiled result, test reads the .mocharc.json. Four lines, the whole lifecycle.

The common thread#

The order behind it is simple: TypeScript checks at compile time and disappears; in tsconfig.json, strict and esModuleInterop carry the most weight; @types/node gives the Node APIs types in the first place; and the tests run via the register hook or the compiled output.

The mistake I see most often is not the complicated generic type but the silent any that spreads without strict until nothing is left of type safety. If you adopt the baseline from this article, that is, strict: true, esModuleInterop: true, @types/node and a clean separation of outDir and rootDir, you move the place where errors show up: to your desk instead of to the user. This is not a formality; it is the actual effect – shorter feedback loops, less friction in review and higher quality in the code that actually ships. The limit is part of it, because the contract pays off where code lives long and passes through many hands, not in the throwaway script. If you know that limit, you get exactly what TypeScript in Node promises: making errors visible early instead of passing them through to runtime.

Further reading#

Revised and translated from German with the help of AI.