Node.js TypeScript
Node.js TypeScript
TypeScript is a programming language built on top of JavaScript that adds:
-
Static typing
-
Interfaces
-
Classes
-
Compile-time error checking
-
Better tooling & IntelliSense
Node.js works extremely well with TypeScript, especially for large backend projects.
✅ 1. Install TypeScript
Globally:
Locally in a project:
✅ 2. Initialize TypeScript in a Node.js Project
This generates:
This file controls TypeScript behavior (ES target, module system, root folders, strict mode, etc.)
✅ 3. Important tsconfig.json Settings (Node.js)
Recommended settings:
Meaning:
-
target: ES version output
-
module: Node uses CommonJS
-
outDir: compiled
.jsfiles -
rootDir: where
.tssource files stay -
strict: enable full type checking
-
esModuleInterop: allows
import express from "express"
✅ 4. Create Your First TypeScript File
Create a folder and file:
Example:
✅ 5. Compile TypeScript to JavaScript
This generates:
✅ 6. Run the Compiled JavaScript With Node
🚀 7. Auto-compile & Auto-run (ts-node + nodemon)
Install useful packages:
Run TypeScript directly without compiling:
For auto-reload, add this in package.json:
Run development mode:
✔️ 8. Using TypeScript with Node.js Modules
Importing built-in modules:
Exporting functions:
Importing:
✔️ 9. Typing Objects & Functions
✔️ 10. Interfaces
✔️ 11. Classes in TypeScript
✔️ 12. Using Express with TypeScript
Install types:
Example app.ts:
⭐ Summary Table
| Feature | Purpose |
|---|---|
| TypeScript install | Setup project |
| tsc –init | Create tsconfig.json |
| ts-node | Run TS without compiling |
| nodemon | Auto-restart |
| Strong typing | Catch errors early |
| Interfaces/Types | Better structure |
| Express + TS | Large scalable apps |
