TypeScript with Node.js

Topic 1 of 3 in TypeScript in practice7 min readIntermediateFree course

Overview

Node.js is where TypeScript started to become the default, and in 2026 the experience is simpler than ever: Node runs TypeScript files directly. This lesson pulls together what you’ve learned into the shape of a real Node project — how type stripping works and its limits, the typed built-in modules, configuration, and the scripts that tie it together.

A modern TypeScript project on Node.js. package.json has “type”: “module” and scripts: “start”: “node src/server.ts”, “check”: “tsc”, “test”: “vitest run”. tsconfig.json has “module”: “nodenext”, “noEmit”: true, “allowImportingTsExtensions”: true, “erasableSyntaxOnly”: true, “verbatimModuleSyntax”: true and “types”: [“node”]. node src/server.ts runs it — Node strips the types; tsc checks it — noEmit, so no output files; vitest run tests it. Imports use the real file names (./store.ts). erasableSyntaxOnly forbids enums and other code-generating syntax.

How Node runs TypeScript

Since Node 22.18 (and in every later release line, including Node 26 LTS), node app.ts works without flags. Node strips the type annotations — replacing them with whitespace, so line and column numbers stay correct in stack traces — and runs the JavaScript that’s left.

It does not type-check:

TypeScript
// w.ts
const x: number = "oops";
console.log(x);
Terminal
node w.ts      # prints: oops
npx tsc        # error TS2322: Type 'string' is not assignable to type 'number'.

What type stripping can’t do

Because Node only removes types, a few things don’t work — and the tsconfig used throughout this course makes tsc report them in advance:

Limitation Error from Node Caught by
enum, namespace with values, parameter properties ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX erasableSyntaxOnly
Importing a type without type does not provide an export named … verbatimModuleSyntax
Imports without extensions (./util) ERR_MODULE_NOT_FOUND module: nodenext
tsconfig paths aliases ERR_MODULE_NOT_FOUND — Node doesn’t read tsconfig use package.json "imports" (#lib/*) instead

Node doesn’t read tsconfig.json at all. (An older --experimental-transform-types flag, which converted enums and similar syntax, has been removed in recent Node versions.) If you need the full TypeScript syntax at run time, use tsx (npx tsx app.ts), Bun or Deno — or compile with tsc.

Typed built-in modules

@types/node (listed in tsconfig’s "types") types every built-in module. Import them with the node: prefix:

TypeScript
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createServer } from "node:http";

const text = await readFile(join("data", "notes.txt"), "utf8");   // string
const bytes = await readFile("logo.png");                         // Buffer — different overload

Overloads give you precise types: passing an encoding returns a string, omitting it returns a Buffer.

Command-line arguments with parseArgs

util.parseArgs parses arguments and is typed from the options you declare:

TypeScript
import { parseArgs } from "node:util";

const { values, positionals } = parseArgs({
  options: {
    top: { type: "string", short: "t", default: "5" },
    verbose: { type: "boolean", default: false },
  },
  allowPositionals: true,
});

values.top;        // string (it has a default)
values.verbose;    // boolean
positionals;       // string[]

Values are strings or booleans — convert and validate numbers yourself.

A typed HTTP server

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

function sendJson(res: ServerResponse, status: number, body: unknown): void {
  res.writeHead(status, { "content-type": "application/json" });
  res.end(JSON.stringify(body));
}

const server = createServer((req: IncomingMessage, res: ServerResponse) => {
  if (req.method === "GET" && req.url === "/health") {
    sendJson(res, 200, { ok: true });
    return;
  }
  sendJson(res, 404, { error: "Not found" });
});

server.listen(3000, () => console.log("Listening on http://localhost:3000"));

The final project builds a complete API on exactly this foundation. Frameworks such as Fastify, Hono and Express (with @types/express) add routing and middleware with full types.

Configuration and environment variables

process.env is typed as Record<string, string | undefined> — every variable might be missing, and every value is a string. Validate them once, at start-up:

TypeScript
import { z } from "zod";

const Env = z.object({
  PORT: z.coerce.number().int().default(3000),
  DATABASE_URL: z.url(),
  LOG_LEVEL: z.enum(["debug", "info", "warn"]).default("info"),
});

export const config = Env.parse(process.env);   // crashes early with a clear message if misconfigured

Node can also load a .env file for you: node --env-file=.env src/server.ts.

Project scripts

JSON
{
  "type": "module",
  "scripts": {
    "dev": "node --watch src/server.ts",
    "start": "node src/server.ts",
    "check": "tsc",
    "test": "vitest run",
    "lint": "eslint ."
  }
}
  • node --watch restarts the program when files change — no extra tool needed.
  • tsc (with noEmit) checks the whole project; run npx tsc --watch in a second terminal while developing, or rely on your editor.
  • In production, you can run the .ts files directly too. Teams that prefer to deploy plain JavaScript compile with tsc (or bundle with esbuild) in a build step — see Building and publishing.

Debugging

Because type stripping preserves positions, stack traces point at the right lines of your .ts files with no source maps needed. node --inspect src/server.ts lets you set breakpoints in Chrome DevTools or VS Code, directly in the TypeScript source.

Remember: Node runs your TypeScript; tsc checks it. Stick to erasable syntax, mark type imports, use node: built-ins with their types, and validate everything that comes from outside the program.

Exercise

A typed command-line word counter

Build src/wordfreq.ts, run as node src/wordfreq.ts <file> [--top N] [--min-length N]. Use parseArgs from node:util for the options (top default "5", min-length default "1") and the file name. Read the file with readFile from node:fs/promises; if it doesn’t exist, print Cannot read <file> to stderr and set process.exitCode = 1. Count words case-insensitively (letters and apostrophes only, ignoring words shorter than min-length) in a Map<string, number>, and print the top N as word count, padded so counts line up. Validate that top is a positive integer and print a usage message otherwise. Check it with tsc and run it on a sample file.

TypeScript
// src/wordfreq.ts
import { readFile } from "node:fs/promises";
import { parseArgs } from "node:util";

const { values, positionals } = parseArgs({
  options: {
    // top, min-length
  },
  allowPositionals: true,
});

Summary

  • Node.js 22.18+ runs .ts files directly by stripping types — no build step, but also no type checking.
  • Type stripping supports only erasable syntax: no enums, namespaces or parameter properties; type imports must be marked type; imports use .ts extensions.
  • @types/node types every built-in module: import them with the node: prefix.
  • Validate untrusted inputs — environment variables, arguments, request bodies — at the edges of the program.
  • A typical setup: node --watch for development, tsc for checking, Vitest for tests.