Getting started with Typescript and Express

There are many tutorials in how to get started with Typescript and Express, but I still wish to contribute with my own favorite for how to set up a project even if it’s a microservice or a bit larger piece of code. To fully understand my setup, I will need to publish a couple of posts so here we go.

Why Typescript?

As a developer for many years, I like to be able to discover any problems early and to be able to use a type safe code even when building a small project that would be easy to create just in plain Javascript. After discovering Typescript, it allows me to better interoperate with types from different languages in the world of REST interfaces.

Typescript does a great job in discovering problems before they happen by compiling and the output is still understandable as javascript code.

What about express?

The express server is really quick and neat to set up and start using. It is fast and does its job really good. It works well in a Docker environment, but is more or less still required to have a proxy in front of it in a production environment.

Getting started

First, you need to have npm to be able to install and run the nodejs infrastructure. Once you download nodejs, npm is included. It is the only native package that you need to install, even if I recommend using an editor such as Visual Studio Code.

Once nodejs is installed, you can create your first project. We will be using the command line to build this.

First we need to create a new application using a package. This is done by running the command “npm init -y” to init the application with default settings. You can of course edit them later.

fgn@Fredriks-MBP:typescript-project$ npm init -y
Wrote to /Users/fgn/dev/typescript-project/package.json:

{
  "name": "typescript-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Now you need to install typescript. You need to install it globally to support the typescript command to run on your machine.

Issue the command to install typescript on your computer and in the project. The sudo is sometimes required to gain access to writing the files.

sudo npm install typescript -g

If you already have typescript installed globally, you just need to install it as a package.

npm install typescript

Then, to initialize the configuration file for Typescript, you could now use the command to create a new tsconfig.json file with comments and some default options selected. It will be created in the current directory.

tsc --init

Now open your favourite editor and open the file tsconfig.json. Edit the three settings:

“sourceMap”:true,
“outDir”: “./build”,
“rootDir”: “./src”,

This is to have a structure for sources and other files separated.

Now you can add the additional packages to your project before we start writing the code. This will install the types and the package express so that we could get an endpoint up and running.

npm install express @types/express 

The code for the project

The code could be implemented in just one file in this case, but for the upcoming blog posts, we will add some middleware etc to the project.

Create the file src/server.ts that will contain the code for the express server.

mkdir src
code .

Now we will create a simple service that will return just the status of 200 and return a text string of OK when requesting it using HTTP and port 4000.

First we will go through the service row by row and then you will find the complete code below (even if it’s really short).

import express = require('express')

This will import the express server package so that we could refer to it as express in the code.

const app : express.Application = express();
const portNumber: number = 4000;

This will create a new constant, the app that is typed as an express.Application and then assigned to be a new express() server by invoking express() as a method. We also assign the port number here in a constant. Later on, we would get the port number from configuration.

app.get('/', (req, res) => {
  res.send('OK').sendStatus(200);
});

Register a path and the verb “GET” for the request with path /. Once a request hits the service, this method will be invoked in case of path /. It will send back the result to the res variable, which is bound to the result.

In this case, it will return the string “OK” and the status of 200 OK.

app.listen(portNumber, () => {
  console.log(`Listening to port ${portNumber}`);
});

Now it’s time to register the listener of the port configured above. Note the quotes that will allow us to refer to variables within the string as a ${variable} notation.

The complete code is here.

import express = require('express')

const app : express.Application = express();
const portNumber: number = 4000;

app.get('/', (req, res) => {
    res.send('OK').sendStatus(200);
});

app.listen(portNumber, () => {
    console.log(`Listening to port ${portNumber}`);
});

Now it’s time to make the code compile by adding a build task to the project. Open your package.json and add the row to build the project using typescript compiler tsc.

Set the “main” to “build/server.js”, remove the “test” from scripts and add the “start”:”tsc && node ./build/server.js” instead. This is since build/server.js will be the primary file to run the project. Running the start script will later on in the blog post show how to build and start the server.

{
  "name": "typescript-project",
  "version": "1.0.0",
  "description": "",
  "main": "build/server.js",
  "scripts": {
    "start": "tsc && node ./build/server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
   "@types/express": "^4.17.6",
    "express": "^4.17.1",
    "typescript": "^3.9.5"
  }
}

Now run the command to build the project.

npm run start

This will build the file build/server.js which is what is required to be able to run the server. You can then run the server and build it at the same time using the start command.

Testing the service using either a simple tool such as curl or postman will give the result of our service

curl --verbose --get http://localhost:4000

Watching directory for changes

One great feature of programming languages that are not compiles is that once a file is changed, the project is reloaded and it just continues with no extra restarts of the scripts.

This is of course available also when using Typescript by the package ts-node-dev which which do just this. So back to our terminal and install another package and the ts-node to run typescript.

npm install ts-node ts-node-dev

To support running this command instead of the one above, just create a new script in the package.json named “dev” which will run the typescript in development mode watching any changes to any source file with a starting poinf of our server.ts.

“dev”:”ts-node-dev ./src/server.ts”

{
  "name": "typescript-project",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "dev": "ts-node-dev ./src/server.ts",
    "start": "tsc && node ./build/server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.6",
    "express": "^4.17.1",
    "ts-node": "^8.10.2",
    "typescript": "^3.9.5"
  }
}

Now you will be able to run your server and watch for any changes made where it will restart automatically.

npm run dev

Now a change of the source files would result in a restart.

This is all for now and I do hope that you have been able to set up your first Typescript-Express piece of code. In the next post, we will look into middlewares.

The following two tabs change content below.

Fredrik Gustavsson

CEO, IT-consultant at Jolix AB
Software and integration magician with an interest in how to improve commerce in a multi channel environment. Owns his own IT-consultancy business and runs an e-commerce store that has a physical store. Will write blog posts on how to take his own store into the future.