User photo

Setting up Express with Typescript

Typescript is that nice Sunday meal but eaten every day; that's if you use it (you should). That nice smell when you cook those errors so that they don't hurt your stomach (runtime). In this blog, we will be adding that Typescript flavor to Express. Let's cook.

Please note:

To continue, please ensure that you have Nodejs installed in your system. When installing Nodejs, you are also installing npm, keep that in mind.

Initialise the project

Open the folder that you will be cooking in. Create a file called index.js. Let us set the flames by initializing our project with the following command on your terminal:

npm init -y
This will initialise the Nodejs environment.
Your folder should have a package.jon that looks like this:
{ "name": "express_typescript", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
Explaining what this file mean will be out of context of this blog post.
Check the resources on the side bar to learn more about this file.
The name express_typescript is the name of our kitchen (project folder), let me say pot for now. Yours will be different from this one.

Installing express

You can add express in your project with the following command:

npm install express
This will add express to your package.json

Simple express application

Let us add those spices and ingredients, to kick start our meal. Let us create a simple Express application with JavaScript. Here is the code:

const express = require("express"); const app = express(); const PORT = 8000; app.get("/", (request, response) => { response.json({status: "Give me that food already."}) }) app.listen(PORT, () => { console.log(`Running on PORT: ${PORT}`) })
This is a basic express application that sends json data to the / route when you navigate to http://localhost:8000/.
But we need our server to be running for us to see the data. So let us see how we can do that.

Running express

To run your express application, open your terminal and run the following command:

node index.js
This should start the server at port 8080 and you can visit http://localhost:8000 to view the output.
Now that we have our food cooking, let's make it taste nice.

Typescript setup

Let us add that grandma's secret recipe. To add Typescript to your project, simply use the following command on your terminal:

npm install typescript
This will install typescript to your current project.
There is a way to install Typescript globally, but I am not going to use it in this blog because I want it to be accessible to people who do not have Typescript installed globally.
Please note:

Nodejs does not understand Typescript, I have covered this on one of my blogs titled How to setup a Typescript Project.

Installing types

Let us add those spices that trigger your taste buds in a very pleasant way. In order for Typescript to work, we need to add types (type definitions) to the packages we are using. Without installing the types, you are basically using JavaScript in the name of Typescript. But we want those Typescript types; we are cooking something here; don't play. To install the types, run the following command on your terminal:

npm install -D @types/node @types/express
This will add types for node and for express, enabling us to have type definitions.
The -D will install the types as dev dependencies, meaning they will only be used in development not in production.
Please note:

Installing types is very important for every Typescript project you create. This allows you to use type definitions which are what Typescript use. It ain't called Typescript if your not going to use types.

Using Typescript

Now that Typescript and types are installed, let us make a few changes. Change index.js to index.ts. After this change, change the code a bit to use Typescript.

import express from "express"; const app = express(); const PORT = 8000; app.get("/", (request, response) => { response.json({status: "Serve me that food already."}) }) app.listen(PORT, () => { console.log(`Server running at PORT: ${PORT}`) })
Instead of using require we are now transitioning to import because that is what Typescript use.

Typescript environment

We need to set up our dining table to serve the food. We need to enable a Typescript environment, and you will see why later on. To setup a Typescript environment, run the following command:

tsc --init --rootDir ./ --outDir dist
This will create a file called tsconfig.json in your project folder.
The tsc is a typescript command that we use for anything typescript, just like we would use node for everything node and npm for everything npm
The —init flag, is used to initialize the configuration file that was created.
The —rootDir ./ flag specifies where we will be storing our typescript file, in our case they are found on the ./ folder.
The —outDir dist flag specifies where will be storing our converted JavaScript files, in our case we want to store them in the dist folder.

Converting Typescript to JavaScript

Let's have a taste of our cooking pot. Now that we have our environment setup and have installed everything we need, let us convert the Typescript to Javascript. In order to convert Typescript to Javascript, we use the following command in your terminal:

npx tsc
After running this command, you should see a index.js file created inside dist folder that we specified when setting up Typescript environment.
Then we can run the converted dist/index.js because Nodejs understands JavaScript but not Typescript.
Let us run the dist/index.js file on our terminal.
node dist/index.js

Automating the process

Start plating up the food to serve. The file package.json has what we call scripts which we can use to automate the process of converting the Typescript file and also running the JavaScript file. Let us customize package.json to something like this:

{ "main": "index.ts", "scripts": { "build": "npx tsc", "preserve": "npm run build", "serve": "npx tsc --watch & node dist/index.js" }, }
We have changed the index.js to index.ts on the main.
We have added scripts: First we want to convert Typescript to JavaScript using the build. Then run index.js with serve but before serve runs, we want to build first. Hence you see the preserve on the code.
On the serve, there is npx tsc --watch. This is a command used to always check for changes made to your Typescript files and restart your server without you having to kill the server and restart again. But the problem here is that we are keeping track of TypeScript but not JavaScript. So we need to always check the changes in our JavaScript files.

Tracking JavaScript

To track changes in our JavaScript, we will use a package called nodemon, which we will install on npm (node package manager). You can install nodemon with the following command:

npm install -D nodemon
This will install nodemon to your package.json. At this point, you already know that the -D flag means.
Let us update our scripts with one simple command.
{ "main": "index.ts", "scripts": { "build": "npx tsc", "preserve": "npm run build", "serve": "npx tsc --watch & nodemon dist/index.js" }, }
This will now keep track of the Typescript with the npx tsc --watch and the JavaScript with nodemon dist/index.js.

Running our express application

Let's eat, we have cooked. To run our express application, simply run the following command in your terminal:

npm run serve
This will add watch for changes in your Typescript files.
Update your JavaScript based on those changes.
Re-run your server.
This process is automated thanks to scripts.

Conclusion

I wish that one day Nodejs would integrate Typescript so that we do not have to go through such pain to set it up, but here we are. You can now use Typescript for your Express applications. I hope I helped you understand the whole setup, because there is no use setting up something you do not understand. If you have any questions, comments, or thoughts, feel free to add them in the comment section. Your feedback to me is vital so that I can adapt to helping you better. Have a lovely day and a great week ahead.