TypeScript with Node.js

🟢 TypeScript with Node.js

Using TypeScript with Node.js helps you build scalable, type-safe backend applications with fewer runtime errors and better developer experience.

🧠 Why Use TypeScript with Node.js?

✅ Strong typing for backend logic
✅ Better auto-completion & refactoring
✅ Early error detection (compile time)
✅ Easier maintenance for large projects


📦 Step 1: Create a Node.js Project

mkdir ts-node-app
cd ts-node-app
npm init -y

📥 Step 2: Install Required Packages

Install TypeScript & Node types

npm install --save-dev typescript @types/node

(Optional but Recommended)

npm install --save-dev ts-node nodemon
Package Purpose
typescript TS compiler
@types/node Node.js type definitions
ts-node Run TS directly
nodemon Auto-restart server

⚙️ Step 3: Create tsconfig.json

npx tsc --init

Recommended Configuration

{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "./src",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true
}
}

📁 Step 4: Project Structure

ts-node-app/

├── src/
│ └── index.ts

├── dist/
│ └── index.js

├── tsconfig.json
└── package.json

✍️ Step 5: Write Node.js Code in TypeScript

src/index.ts

import http from "http";

const server = http.createServer((req, res) => {
res.writeHead(200, { “Content-Type”: “text/plain” });
res.end(“Hello TypeScript + Node.js”);
});

server.listen(3000, () => {
console.log(“Server running on port 3000”);
});


▶️ Step 6: Run the Project

Option 1: Compile then Run

npx tsc
node dist/index.js

Option 2: Run Directly with ts-node

npx ts-node src/index.ts

🔁 Step 7: Auto Reload with Nodemon

Add this script in package.json:

"scripts": {
"dev": "nodemon src/index.ts"
}

Run:

npm run dev

🌐 Using TypeScript with Express (Very Common)

Install Express

npm install express
npm install --save-dev @types/express

Example (src/app.ts)

import express, { Request, Response } from "express";

const app = express();

app.get(“/”, (req: Request, res: Response) => {
res.send(“Hello from Express + TypeScript”);
});

app.listen(3000, () => {
console.log(“Server running on port 3000”);
});


🧪 Environment Variables (process.env)

const port: number = Number(process.env.PORT) || 3000;

📌 Install types already covered by @types/node.


🔑 Summary

Task Tool
Backend runtime Node.js
Language TypeScript
Compiler tsc
Run TS ts-node
Hot reload nodemon
Types @types/node

⭐ Best Practices

✔ Always install @types/node
✔ Use strict: true
✔ Separate src and dist
✔ Use ts-node only for development
✔ Compile to JS for production

You may also like...