bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/JS & TS Features
Node.js•JS & TS Features

Node.js TypeScript

What is TypeScript?

TypeScript is a superset of JavaScript that adds optional static typing. It helps you catch errors early and write safer, more maintainable code.

Take a look at our

TypeScript tutorial for more details. Using TypeScript with Node.js To use TypeScript in Node.js projects, you need to install TypeScript and a type definition manager:

Formula

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

Write your code in.ts files and compile them to JavaScript with: tsc yourfile.ts

Setting Up a TypeScript Project

Formula

1. Initialize a new Node.js project npm init - y
2. Install TypeScript and type definitions npm install -- save - dev typescript @types/node
  1. Initialize TypeScript configuration npx tsc --init

TypeScript Basics

  1. Basic Types

Formula

// Primitive types let isDone: boolean = false;
let count: number = 10;
let name: string = 'TypeScript';
// Arrays let numbers: number[] = [1, 2, 3];
let names: Array<string> = ['Alice', 'Bob'];
// Tuples let user: [string, number] = ['Alice', 25];
// Enums enum Color {Red, Green, Blue}
let color: Color = Color.Green;
  1. Interfaces and Types
// Interface interface User {
id: number;
name: string;
email?: string;  // Optional property
}
// Type alias type Point = {
x: number;
y: number;
};
// Using the interface function printUser(user: User) {
console.log(`User: ${user.name}`);
}

TypeScript with Node.js

  1. Creating a Simple HTTP Server
// server.ts import http from 'http';
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, TypeScript!');
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
  1. Using TypeScript with Express

Formula

# Install required packages npm install express npm install -- save - dev @types/express
// app.ts import express, { Request, Response } from 'express';
interface User {
id: number;
name: string;
}
const app = express();
app.use(express.json());

Formula

// In - memory database let users: User[] = [];

// Get all users app.get('/users', (req: Request, res: Response) => {

res.json(users);
});
// Add new user app.post('/users', (req: Request, res: Response) => {
const user: User = req.body;
users.push(user);
res.status(201).json(user);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

TypeScript Configuration tsconfig.json

{
"compilerOptions": {
"target": "es2018",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}

Key Compiler Options:

target : Specify ECMAScript target version module : Specify module code generation strict : Enable all strict type checking options outDir : Redirect output structure to the directory rootDir : Specify the root directory of input files Why Use TypeScript with Node.js?

Benefits of TypeScript:

Type Safety

: Catch errors at compile time rather than runtime

Better IDE Support

: Superior autocompletion and code navigation

Self-Documenting Code

: Types serve as documentation

Easier Refactoring

: Safely rename variables and update code

Gradual Adoption

: Add types incrementally to existing JavaScript code

When to Use TypeScript:

Large codebases with multiple developers

APIs where type safety is critical

Projects that will be maintained long-term

When working with complex data structures

Previous

Node.js Process Management

Next

Node.js Advanced TypeScript