Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 96 ยท TypeScript in Practice

TypeScript with Node.js

Use TypeScript with Node.js - @types/node, typing fs, path and process, reading input, running .ts files with Node's type stripping, and building a small typed CLI tool.

Node.js is where a lot of TypeScript runs: web servers, build scripts, command-line tools and serverless functions. The combination is a natural fit, because Node's built-in modules have detailed type definitions, and modern Node versions can even run .ts files directly.

In this lesson you'll set up a Node project for TypeScript, learn what the @types/node package gives you, type the everyday modules (fs, path, process), handle Node's errors safely, and see what Node's built-in type stripping can and cannot do. At the end you'll put it together in a small command-line tool.

Every example in our editor is already a Node program: the TypeScript 7 compiler type-checks it, then Node 24 runs it with @types/node available. So unlike the browser lessons, everything here is fully runnable.

Setting up a Node project

A typical TypeScript Node project needs three things: TypeScript itself, the Node type definitions, and a tsconfig.json.

Terminal
npm init -y
npm install --save-dev typescript @types/node
npx tsc --init

@types/node contains declaration files (see declaration files) describing every built-in module. Install the major version that matches the Node version you deploy on, for example @types/node@24 for Node 24, so you don't get types for functions your runtime doesn't have.

A good starting tsconfig.json for a modern Node project looks like this:

JSON
{
  "compilerOptions": {
    "target": "es2024",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "types": ["node"],
    "strict": true,
    "outDir": "dist",
    "rootDir": "src",
    "sourceMap": true,
    "skipLibCheck": true,
    "verbatimModuleSyntax": true
  },
  "include": ["src"]
}

"module": "nodenext" tells TypeScript to follow Node's own rules: whether a file is an ES module or CommonJS depends on the nearest package.json "type" field and the file extension (.mts is always ESM, .cts always CommonJS). Most new projects add "type": "module" to package.json and write ES modules everywhere. The tsconfig and modules lessons explain these options in detail.

With nodenext, relative imports need a file extension, and you write the extension of the output file: import { parse } from './parser.js', even though the source file is parser.ts. The option rewriteRelativeImportExtensions lets you write ./parser.ts instead and has the compiler rewrite it.

Typing the built-in modules

Import built-in modules with the node: prefix. It makes clear the module is part of Node, not an npm package, and the types come along automatically:

TypeScript fs and path are fully typed

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.

It prints:

TEXT
data   .json  12 bytes
notes  .txt   18 bytes
[ 'buy milk', 'call Ana' ] 18

Notice how precise the types are. readFileSync is an overloaded function: passing the encoding 'utf8' selects the overload that returns string, and leaving it out selects the one returning Buffer. If you assigned the second call to a string, you'd get a compile error, not a runtime surprise.

The promise-based versions live in node:fs/promises and return Promise<string>, Promise<string[]> and so on. In an ES module, you can await them at the top level:

TypeScript
import { readFile } from 'node:fs/promises';

const config = await readFile('config.json', 'utf8'); // string

process: argv, env and exit codes

The global process object is typed too, and its types encode real runtime facts:

  • process.argv is string[]: everything on the command line is text.
  • process.env maps names to string | undefined, because any variable might be missing.
  • process.exitCode is a number you set to report failure without stopping immediately.

That means TypeScript forces you to handle missing variables, which is exactly the bug that crashes servers in production:

TypeScript Reading environment variables safely

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.

It prints:

TEXT
{ mode: 'development', port: 8080, workers: 2 }
Missing environment variable DATABASE_URL

Try deleting the if in requireEnv. The return value line then fails with Type 'string | undefined' is not assignable to type 'string', because the compiler won't let a possibly missing value escape as a string.

Writing process.env.APP_MODE = 'development' only works for strings. Assigning a number is a type error, because Node would silently turn it into a string anyway.

Reading standard input

Command-line tools often read data piped into them. The simplest way is to read file descriptor 0 (stdin) all at once. In our editor, the TryIt's input box is that stdin:

TypeScript Summing numbers from stdin

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 output is:

TEXT
total: 45.5
line 3: "abc" is not a number

For line-by-line processing of big inputs, node:readline gives you an async iterator, so you can write for await (const line of rl). Each line is typed as string. You'll meet async iteration in iterators and generators.

Handling Node errors

Most Node failures are thrown as Error objects with extra properties: code (like 'ENOENT' for "file not found"), path and syscall. Under strict mode, the catch variable is unknown (see error handling), so you have to narrow before you look at code. A small type guard does it neatly:

TypeScript Narrowing a Node system error

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.

It prints:

TEXT
no settings file, using defaults
EISDIR during read

NodeJS.ErrnoException is an interface from @types/node that extends Error with optional code, errno, path and syscall properties. The guard only checks what really matters at runtime: that the value is an Error and has a code.

Running TypeScript directly with Node

You don't always need a build step. There are three ways to run a .ts file:

Approach Type-checks? Notes
tsc then node dist/main.js Yes The classic production setup. Output is plain JavaScript.
node main.ts (type stripping) No Built into Node 22.18+, 23.6+ and 24. Fast, no dependencies.
npx tsx main.ts No A popular npm tool (built on esbuild) that supports every syntax and tsconfig paths.

Type stripping

Node's type stripping replaces type annotations with whitespace and runs the result. Because it only removes things, it has limits:

  • No type checking at all. A file full of type errors runs anyway. Run tsc --noEmit (in your editor, in CI or as a pre-commit step) to catch them.
  • Only erasable syntax. enum, namespace blocks with code, and constructor parameter properties produce JavaScript, so Node rejects them. Enable "erasableSyntaxOnly": true in tsconfig.json to have tsc flag them for you (see what's new).
  • Type-only imports must say so. Write import type { User } from './user.ts'. Turn on verbatimModuleSyntax so the compiler enforces it.
  • Real file extensions. Imports must name the actual file, ./user.ts. Combine allowImportingTsExtensions with noEmit, or use rewriteRelativeImportExtensions if you also compile with tsc.
  • tsconfig.json is ignored. Node doesn't read it, so options like paths have no effect.
Terminal
node src/main.ts                 # run directly (Node 24)
npx tsc --noEmit                 # type-check separately
npx tsx watch src/main.ts        # tsx: rerun on every change

A popular modern setup is: run with Node's type stripping or tsx during development, type-check with tsc --noEmit in CI, and compile with tsc (or a bundler) for production. The older ts-node package type-checks while it runs, but it's slower and less common in new projects.

A small CLI tool

Let's combine everything into a tool called wordfreq: it reads text from stdin and prints the most common words. Options come from the command line, parsed with util.parseArgs, which is built into Node and infers the type of the parsed options from the config you pass it.

Our editor can't pass real command-line arguments, so the example hands parseArgs an args array explicitly. In a real tool you'd leave args out and it would read process.argv.

TypeScript wordfreq: a typed command-line tool

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.

It prints:

TEXT
Top 3 words (length >= 3):
  5  the
  3  dog
  3  fox

Look at the types you never wrote: values.top is string, values.ignoreCase is boolean, and a typo like values.tpo is a compile error. parseArgs is a generic function whose return type is computed from the options object using mapped and conditional types. Because each option has a default, the values are never undefined.

To ship this as a real command, you'd compile it to dist/wordfreq.js, add a #!/usr/bin/env node line at the top of the source, and point the "bin" field of package.json at the output file.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of process.env.API_KEY?

    Any environment variable might be missing, so @types/node types each one as string | undefined. You must narrow before using it as a string.
  2. 2. What does readFileSync(path) (without an encoding) return?

    readFileSync is overloaded. Without an encoding the overload returns a Buffer; with 'utf8' it returns a string.
  3. 3. You run node main.ts on a file that contains a type error. What happens?

    Node only strips the types away and runs the result. Use tsc --noEmit to find type errors.
  4. 4. Which of these can Node's type stripping NOT run?

    Enums generate runtime code, so they cannot simply be erased. Interfaces, generics and import type are pure type syntax and are removed.
  5. 5. Inside catch (error), why can't you read error.code directly in strict mode?

    With useUnknownInCatchVariables (part of strict), catch variables are unknown. A type guard such as error instanceof Error && 'code' in error narrows it.

Summary

  • Install typescript and @types/node (matching your Node major version), and use "module": "nodenext" so TypeScript follows Node's module rules.
  • Import built-ins with the node: prefix; their types are precise, for example readFileSync returns string with an encoding and Buffer without.
  • process.env values are string | undefined and process.argv is string[]: validate and convert them at the edge of your program.
  • Read stdin with readFileSync(0, 'utf8') or node:readline; narrow caught errors to NodeJS.ErrnoException before checking code.
  • node main.ts runs TypeScript by stripping types: fast, but no type checking and only erasable syntax. Pair it with tsc --noEmit.
  • util.parseArgs infers option types from its config, giving you a typed CLI without any dependency.

Next: TypeScript in the Browser (DOM)