In this article I will share my experience in developing a web backend in Typescript. I will share how I developed a project completely in Node+Typescript (NodeTs) and another project on using typescript in an existing NodeJs applications.
A prior knowledge of NodeJs, Typescript and some idea of Express and is necessary for this article. I am using a MacOS so the commands should work on Linux systems too. It is assumed that you already have npm and node setup on your machine.
Why Typescript for Backend?
Using typescript enabled us to use the OOP principles more easily. At the same time we were able to catch a lot of code issues at compile time.
Getting Started with a Hello World
We will create a folder named nodets to hold our code in a directory of your choosing. Inside the folder, create a package.json and main.ts files.
Open the package.json in your favourite editor and enter the following lines:
The package.json now has the typescript and ts-node package needed to compile and build the code. Along with these dependencies we will add node types, for typescript to understand the types of the node module code.
Next, enter the code below in the main.ts file.
For our hello world example we create a Main class with a hello() function. We then create an instance of this class and call the hello method.
Run the following command to install the packages and execute the script.
You should see `Hello World` on your screen.
So this is it. All you need to get started. We register ts-node for node to understand that it’s dealing with typescript. The execution will take some time to start up since node will have to check for type issues, etc before executing the code.
Using the code from GitHub
The code used in this article can be found here. I have tagged the various steps of the code. The code for the section above is tagged as v1. You can use the following commands to check it out.
$ git clone firstname.lastname@example.org:udaykale/nodets-blog.git
$ git checkout tags/v1
It is however, recommended to do it yourself first, unless you are stuck for long.
Adding Express to the Mix
Most web development for node happens using express framework. So in this step we will setup an express server in typescript.
First we will add express and its types to the package.json.
Note: The changes from previous section are colour marked int the margin
Apart from the express changes we have also added start script so that we can run the main file using
$ npm run start
This section is tagged with v2 in the git repo.
Create a new file named insidejs.js alongside main.js. Add the following function into it.
Calling the http://localhost:4000/inside-js should return an “Inside JS” message.
This section is tagged with v3 in the git repo.
Happy Coding!! :)