Using TypeScript with Node.js
1. Setting Up TypeScript
| Step | Command |
|---|---|
| Install | npm i -D typescript @types/node |
| Init | npx tsc --init |
| Build | npx tsc |
2. Configuring tsconfig.json
Example
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist",
"rootDir": "src",
"sourceMap": true
},
"include": ["src/**/*"]
}
3. Using ts-node
| Command | Use |
|---|---|
npx ts-node src/index.ts | JIT compile + run |
node --loader ts-node/esm | ESM support |
ts-node-dev | Watch + reload |
4. Using tsx for Fast Execution
| Command | Use |
|---|---|
npx tsx src/index.ts | esbuild-powered, fast |
npx tsx watch src | Watch mode |
| Loader | node --import tsx src/x.ts |
5. Type Definitions (@types/node)
| Detail | Notes |
|---|---|
| Match major version | @types/node@^20 for Node 20 |
| Includes | All node:* module types |
6. Compiling TypeScript
| Tool | Output |
|---|---|
tsc | JS + .d.ts |
esbuild / swc | Fast transpile (no type-check) |
| Recipe | Fast bundler for build, tsc --noEmit for type-check |
7. Using TypeScript with ESM
| Setting | Detail |
|---|---|
"type": "module" in package.json | Treat .js as ESM |
"module": "NodeNext" | Match runtime resolution |
| Imports | Must include .js extension in source |
8. Type Checking Without Compilation
| Command | Use |
|---|---|
tsc --noEmit | CI type-check step |
tsc --watch --noEmit | Editor-like loop |
| Native TS in Node | --experimental-strip-types v22.6+ |
9. Using TypeScript Decorators
| Spec | Detail |
|---|---|
| Stage-3 (TS 5+) | Default; native ECMAScript |
| Legacy (experimentalDecorators) | Required by NestJS, TypeORM, etc. |
10. Debugging TypeScript
| Step | Detail |
|---|---|
| Enable source maps | "sourceMap": true |
| VS Code | Auto-maps stack frames to .ts |
| Run via tsx / ts-node | Source maps generated automatically |