TypeScript with Node.js
🟢 TypeScript with Node.js
🧠 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
📥 Step 2: Install Required Packages
Install TypeScript & Node types
(Optional but Recommended)
| 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
Recommended Configuration
📁 Step 4: Project Structure
✍️ Step 5: Write Node.js Code in TypeScript
src/index.ts
▶️ Step 6: Run the Project
Option 1: Compile then Run
Option 2: Run Directly with ts-node ⭐
🔁 Step 7: Auto Reload with Nodemon
Add this script in package.json:
Run:
🌐 Using TypeScript with Express (Very Common)
Install Express
Example (src/app.ts)
🧪 Environment Variables (process.env)
📌 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
