TypeScript Integration with Node.js Examples

Discover practical examples of TypeScript integration with Node.js for enhanced coding efficiency.
By Jamie

Examples of TypeScript Integration with Node.js Examples

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.

Example 1: Building a Simple HTTP Server

Context

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}/`);
});

Notes

  • Make sure to compile the TypeScript code into JavaScript before running it. Use the command tsc server.ts if your file is named server.ts.
  • You can expand this server by handling different routes and methods.

Example 2: Creating a RESTful API

Context

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}`);
});

Notes

  • Install the necessary packages with npm install express @types/express.
  • This API can be tested using Postman or any other API testing tool.

Example 3: Connecting to a MongoDB Database

Context

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);

Notes

  • Ensure MongoDB is installed and running on your machine.
  • You need to install Mongoose with npm install mongoose @types/mongoose.
  • This example includes a function to create a new user, which can be expanded further to include more CRUD operations.