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:

npm install -g typescript

Locally in a project:

npm install typescript --save-dev

2. Initialize TypeScript in a Node.js Project

npx tsc --init

This generates:

tsconfig.json

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 .js files

  • rootDir: where .ts source files stay

  • strict: enable full type checking

  • esModuleInterop: allows import express from "express"


4. Create Your First TypeScript File

Create a folder and file:

src/app.ts

Example:


 


5. Compile TypeScript to JavaScript

npx tsc

This generates:

dist/app.js

6. Run the Compiled JavaScript With Node

node dist/app.js

🚀 7. Auto-compile & Auto-run (ts-node + nodemon)

Install useful packages:

npm install --save-dev ts-node nodemon

Run TypeScript directly without compiling:

npx ts-node src/app.ts

For auto-reload, add this in package.json:



 

Run development mode:

npm run dev

✔️ 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:

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

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

You may also like...