Node.js TypeScript

TypeScript is JavaScript with types. A type states what kind of value a variable holds, such as text or a number. The TypeScript compiler checks your code before it runs and catches mistakes early. Large Node.js projects use TypeScript for safer, clearer code.

The Spell Checker Idea

A spell checker underlines mistakes while you write, long before a reader sees them. TypeScript does the same for code. It underlines a wrong value in your editor, so the bug never reaches your users.

 JavaScript:  write --> run --> crash --> find bug
 TypeScript:  write --> editor warns --> fix --> run

A Bug TypeScript Catches

function double(n) {
  return n * 2;
}
console.log(double("five"));   // NaN, found only at runtime
function double(n: number): number {
  return n * 2;
}
console.log(double("five"));   // Error in the editor

How TypeScript Runs

Node.js reads JavaScript only. A compiler converts .ts files into .js files. The type checks vanish during conversion.

 app.ts --> [ TypeScript compiler ] --> app.js --> node app.js
 (typed)        checks and converts      (plain)

Set Up a Project

mkdir ts-app
cd ts-app
npm init -y
npm install typescript tsx @types/node --save-dev
npx tsc --init
  • typescript provides the compiler.
  • tsx runs .ts files directly during development.
  • @types/node adds type information for Node.js functions.

Key Settings in tsconfig.json

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

The strict setting turns on the most helpful checks. Keep it on.

Basic Types

const name: string = "Asha";
const age: number = 25;
const active: boolean = true;
const scores: number[] = [90, 85, 70];
const pair: [string, number] = ["Ravi", 30];   // tuple

TypeScript guesses many types by itself. The line const city = "Pune" already counts as a string.

Describe Objects

An interface lists the fields an object must hold.

interface User {
  id: number;
  name: string;
  email?: string;   // optional field
}

const user: User = { id: 1, name: "Asha" };

A missing required field or a wrong type triggers an error.

Type Functions

function greet(user: User): string {
  return "Hello, " + user.name;
}

const add = (a: number, b: number): number => a + b;

Union Types

A union allows several choices.

type Status = "pending" | "paid" | "failed";

function showStatus(s: Status) {
  console.log("Order is " + s);
}

showStatus("paid");      // fine
showStatus("shipped");   // error

Use TypeScript with Express

npm install express
npm install @types/express --save-dev
import express, { Request, Response } from "express";

const app = express();
app.use(express.json());

interface Product {
  id: number;
  title: string;
  price: number;
}

const products: Product[] = [
  { id: 1, title: "Notebook", price: 120 }
];

app.get("/products", (req: Request, res: Response) => {
  res.json(products);
});

app.post("/products", (req: Request, res: Response) => {
  const item: Product = req.body;
  products.push(item);
  res.status(201).json(item);
});

app.listen(3000, () => console.log("Server ready"));

Run and Build

npx tsx src/index.ts       // run during development
npx tsc                    // build into the dist folder
node dist/index.js         // run the built code

Add shortcuts to package.json.

"scripts": {
  "dev": "tsx watch src/index.ts",
  "build": "tsc",
  "start": "node dist/index.js"
}

Folder Layout

ts-app/
  src/
    index.ts
    routes/
    models/
  dist/            (built files)
  tsconfig.json
  package.json

Benefits and Costs

  • Editors suggest fields and warn about mistakes.
  • Refactoring feels safer in big projects.
  • Types document the code for teammates.
  • A build step and a learning curve add some work.

Practice Tasks

  • Convert a small JavaScript function to TypeScript and add types.
  • Create a Book interface and a function that prints a book title.
  • Build a typed Express route that returns an array of users.