Express + TypeScript

Express is a minimal, open source and flexible Node.js web application framework which provides robust features for web and mobile applications.

Let’s brief ourselves with basic knowledge of NodeJS and JavaScript before kicking off with Express -

Install NodeJS

Download the latest version of NodeJS and install in your local machine.

After installation of NodeJS, you can verify the version of node. Now, open command prompt and type command “node --version”.

node --version

Setup ExpressJS

Create blank directory to setup the Express

mkdir my-express-app

cd my-express-app

Now, create package.json file for your application. This package.json file stores some information about your application, scripts command and dependencies of other npm packages.

npm init

When you run the above command, you need to setup the basic information of your application. See below screenshot.

The package.json file will be created as below.

Install the express in the application directive and add it to the dependency list in package.json file.

npm install express -s

Setup the TypeScript

Node.js is an engine that runs Javascript and not Typescript. The node Typescript package allows you to transpile .ts files to .js scripts.

Install the typescript package.

npm install typescript -s

Inside the package.json, add script called tsc:

"scripts": { "tsc": "tsc"},

This change allows to call typescript functions from the command line in the application directive. So we can use the following command:

npm run tsc --init

This command initializes the typescript project by creating the tsconfig.json file.

Install typing for Express

Express and Typescript packages are independent. As a result, Typescript doesn’t “know” types of Express classes. There is a specific npm package for the Typescript to recognize the Express types.

npm install @types/express -s

Let’s start with a simple hello world application.

Open app.ts file and write the below code.

  • Import the express object from express typing.
  • The express() function creates the Express application.
  • The get() function set with simple root route to respond with Hello World! on home page.
    • When someone makes a GET request for the specified path, the callback function runs.
    • The request and response objects represent the HTTP request and response properties.
    • The response.send function causes the response to be sent to the client.
  • The listen function makes the app listen for a connection on the specified port.

Run the below command to execute application.

node app/app.js

Open the browser then visit the URL http://localhost:3000