Express.js is a popular web application framework for Node.js, which is widely used for building web applications and APIs. With the advent of TypeScript, developers have been looking for ways to use it with Express.js for better type safety and improved development experience. In this tutorial, we will explore how to use TypeScript with Express.js.
Prerequisites
Before we start, make sure that you have the following installed on your system:
- Node.js (version 14 or later)
- npm (version 7 or later)
Setting up the Project
Let's start by creating a new project using the following command:
npm init -yThis command will create a new package.json file in your project directory.
Next, we need to install the required dependencies:
npm install express typescript @types/express @types/node --save-dev- express: This is the Express.js framework.
- typescript: This is the TypeScript compiler.
- @types/express and @types/node: These are the TypeScript type definitions for Express.js and Node.js.
Now, create a new src directory in your project and add a new file called index.ts. This will be our main entry point for the application.
Creating the Server
In the index.ts file, let's start by importing the required modules:
import express, { Request, Response } from 'express';Here, we have imported the express module and the Request and Response interfaces from the @types/express module.
Next, let's create an instance of the Express.js application:
const app = express();Now, let's define a simple GET route:
app.get('/', (req: Request, res: Response) => {
res.send('Hello World!');
});Here, we have defined a route that responds with the string 'Hello World!'.
Compiling the TypeScript Code
Before we can run our server, we need to compile the TypeScript code to JavaScript. To do this, add a new script in the package.json file:
"scripts": {
"build": "tsc"
},This script will use the tsc command to compile the TypeScript code to JavaScript.
Running the Server
To run the server, add another script to the package.json file:
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
},
This script will run the compiled JavaScript code using the node command.
Now, run the following command to start the server:
npm run build
npm run startThis will compile the TypeScript code and start the server.
Conclusion
In this tutorial, we have explored how to use TypeScript with Express.js. We started by setting up a new project, installing the required dependencies, and creating a simple server that responds with a message. We then compiled the TypeScript code to JavaScript and ran the server. With TypeScript, we can benefit from better type safety and a more enjoyable development experience.