Using TypeScript with Node.js

1. Setting Up TypeScript

StepCommand
Installnpm i -D typescript @types/node
Initnpx tsc --init
Buildnpx 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

CommandUse
npx ts-node src/index.tsJIT compile + run
node --loader ts-node/esmESM support
ts-node-devWatch + reload

4. Using tsx for Fast Execution

CommandUse
npx tsx src/index.tsesbuild-powered, fast
npx tsx watch srcWatch mode
Loadernode --import tsx src/x.ts

5. Type Definitions (@types/node)

DetailNotes
Match major version@types/node@^20 for Node 20
IncludesAll node:* module types

6. Compiling TypeScript

ToolOutput
tscJS + .d.ts
esbuild / swcFast transpile (no type-check)
RecipeFast bundler for build, tsc --noEmit for type-check

7. Using TypeScript with ESM

SettingDetail
"type": "module" in package.jsonTreat .js as ESM
"module": "NodeNext"Match runtime resolution
ImportsMust include .js extension in source

8. Type Checking Without Compilation

CommandUse
tsc --noEmitCI type-check step
tsc --watch --noEmitEditor-like loop
Native TS in Node--experimental-strip-types v22.6+

9. Using TypeScript Decorators

SpecDetail
Stage-3 (TS 5+)Default; native ECMAScript
Legacy (experimentalDecorators)Required by NestJS, TypeORM, etc.

10. Debugging TypeScript

StepDetail
Enable source maps"sourceMap": true
VS CodeAuto-maps stack frames to .ts
Run via tsx / ts-nodeSource maps generated automatically