TypeScript with Node.js
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.
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:
// w.ts
const x: number = "oops";
console.log(x);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:
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 overloadOverloads 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:
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
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:
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 misconfiguredNode can also load a .env file for you: node --env-file=.env src/server.ts.
Project scripts
{
"type": "module",
"scripts": {
"dev": "node --watch src/server.ts",
"start": "node src/server.ts",
"check": "tsc",
"test": "vitest run",
"lint": "eslint ."
}
}node --watchrestarts the program when files change — no extra tool needed.tsc(withnoEmit) checks the whole project; runnpx tsc --watchin a second terminal while developing, or rely on your editor.- In production, you can run the
.tsfiles directly too. Teams that prefer to deploy plain JavaScript compile withtsc(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;
tscchecks it. Stick to erasable syntax, mark type imports, usenode:built-ins with their types, and validate everything that comes from outside the program.
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.
// src/wordfreq.ts
import { readFile } from "node:fs/promises";
import { parseArgs } from "node:util";
const { values, positionals } = parseArgs({
options: {
// top, min-length
},
allowPositionals: true,
});// src/wordfreq.ts
import { readFile } from "node:fs/promises";
import { parseArgs } from "node:util";
const USAGE = "Usage: node src/wordfreq.ts <file> [--top N] [--min-length N]";
const { values, positionals } = parseArgs({
options: {
top: { type: "string", short: "t", default: "5" },
"min-length": { type: "string", default: "1" },
},
allowPositionals: true,
});
const file = positionals[0];
const top = Number(values.top);
const minLength = Number(values["min-length"]);
function countWords(text: string, min: number): Map<string, number> {
const counts = new Map<string, number>();
for (const word of text.toLowerCase().match(/[a-z']+/g) ?? []) {
if (word.length < min) continue;
counts.set(word, (counts.get(word) ?? 0) + 1);
}
return counts;
}
async function main(): Promise<number> {
if (file === undefined || !Number.isInteger(top) || top < 1 || !Number.isInteger(minLength)) {
console.error(USAGE);
return 2;
}
let text: string;
try {
text = await readFile(file, "utf8");
} catch {
console.error(`Cannot read ${file}`);
return 1;
}
const ranked = [...countWords(text, minLength)].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
const width = Math.max(...ranked.slice(0, top).map(([word]) => word.length));
for (const [word, count] of ranked.slice(0, top)) {
console.log(`${word.padEnd(width)} ${count}`);
}
return 0;
}
process.exitCode = await main();Summary
- Node.js 22.18+ runs
.tsfiles 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.tsextensions. @types/nodetypes every built-in module: import them with thenode:prefix.- Validate untrusted inputs — environment variables, arguments, request bodies — at the edges of the program.
- A typical setup:
node --watchfor development,tscfor checking, Vitest for tests.