TypeScript is a powerful superset of JavaScript that adds static typing to the language, enhancing the development experience, especially in large projects. When integrated with Node.js, TypeScript provides better tooling and helps catch errors early in the development process. Below are three practical examples demonstrating how to integrate TypeScript with Node.js.
This example showcases how to create a basic HTTP server using TypeScript and Node.js. It’s a great starting point for understanding how to set up a TypeScript project with Node.js.
import http from 'http';
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
tsc server.ts
if your file is named server.ts
.In this example, we create a simple RESTful API using Express, a popular web framework for Node.js, with TypeScript. This is useful for building APIs that can serve data to various clients.
import express, { Request, Response } from 'express';
const app = express();
const port = 3000;
app.use(express.json());
interface User {
id: number;
name: string;
}
let users: User[] = [];
app.get('/users', (req: Request, res: Response) => {
res.json(users);
});
app.post('/users', (req: Request, res: Response) => {
const user: User = req.body;
users.push(user);
res.status(201).json(user);
});
app.listen(port, () => {
console.log(`API is running at http://localhost:${port}`);
});
npm install express @types/express
.This example demonstrates how to connect a TypeScript application running on Node.js to a MongoDB database using Mongoose, an ODM (Object Data Modeling) library. This is essential for applications that need to manage data persistently.
import mongoose from 'mongoose';
const uri = 'mongodb://localhost:27017/mydatabase';
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, required: true }
});
const User = mongoose.model('User', userSchema);
const createUser = async (name: string, age: number) => {
const user = new User({ name, age });
await user.save();
console.log('User created:', user);
};
createUser('Alice', 30);
npm install mongoose @types/mongoose
.