TypeScript in Node.js

Written by Sundeep Charan Ramkumar

Sundeep Charan Ramkumar
UpSkillie
Published in
5 min readDec 27, 2019

--

Agenda

  1. Introduction
  2. Why TypeScript?
  3. Integrating into Node.js
  4. Conclusion

Introduction

In this article, we are going to explore what TypeScript is in a nutshell, as well as how it would integrate well with Node.js. We would look up towards the uses, and the advantages TypeScript gives us how it avoids certain pitfalls when compared with regular JavaScript. Furthermore, we would look upon the method to integrate TypeScript to a small Express.js application and make sure that it runs both on TypeScript and Javascript. Let’s begin

Why TypeScript?

Before we move on integrating with Node.js, we must get to know what TypeScript gives us and how it makes a difference when compared with JavaScript. TypeScript is a superset of JavaScript with statically typed features, developed and maintained by Microsoft. TypeScript allows us to fix a specific data type when variables are being declared/initialized. Let’s see an example side by side with TypeScript as well as JavaScript.

The above snippet refers to a standard variable declaration in Javascript.

In TypeScript, we tell the type of input separated by a colon and the type name. Not just that TypeScript has other features like,

  • Intellisense support
  • Error handling during compile time
  • Better Object Oriented Programming techniques.
  • Auto import dependencies, based upon code.

Now that I created a sense of eagerness upon you, let’s wait for no further and dive into the integration part.

Integrating into Node.js

First and foremost, we need to understand that at the end of the day, TypeScript is just plain Javascript behind the scenes, meaning that there is virtually everything that in JavaScript uses. Hence the development workflow is going to be pretty much similar with slight modifications.

Step 1: Initialising NPM

To start a Node.js app, I am pretty sure you guys have Node.js installed, else click here to download. With that setup, let’s move on with the following commands.

This command would ask you specific details from the application name, author, licensing to your git repository URL. Completing it results in this image. Please note that the JSON result varies according to your details.

Alt Text

Step 2: Installing dependencies for the application

Now let’s install the required packages.

The above terminal scripts refer to the packages TypeScript, ts-node which are required for compilation to Javascript and running Typescript code without the requirement to compile respectively. Express requires the other dependencies for spinning up and ensuring to run the script after every saves.

Step 3: Creating a ruleset for TypeScript compilation

There would be some times, we as developers would feel the need for flexibility in the compilation, like some configurations. Luckily TypeScript provides us with a config file as well. This config file enriches the way TypeScript would compile and the accessibility even to stop compiling when met with errors. To create a config file, we need to type in.

Running this would result in the creation of a new file called tsconfig.json under the root directory. Please note that there would be a certain number of options present which are commented to not interfere with the default process, and I highly encourage you to visit the documentation to know in detail of all their usages. However, for demonstration purposes, We look over specific properties inside the file.

  1. target -> The target ES version to which JavaScript should be compiled
  2. outDir -> The directory to which the code must be compiled to
  3. rootDir -> The directory from which TypeScript needs to be compiled
  4. noEmitOnError -> Optional property to not allow compilation if found any errors. (This property is not present on the file itself; hence I request you to type on your own)
  5. noUnusedParameters -> Optional property to ensure there exists no unused function parameters.

To maintain consistency, I would suggest adding “src” as rootDir and “dist” as outDir, and right for the following properties mentioned above.

Step 4: Adding custom npm scripts

Now that we have wired up the configuration and the installation. Let us focus back to package.json’s scripts object. Update it with the following

The build command is responsible for the compilation, dev for development server startup and start script to jumpstart via Javascript.

Step 5: Creating our first TypeScript file

Great! Let’s start building our server under TypeScript. Create a file naming ‘server.ts’ (Name is purely your choice, however, update the filename inside the scripts property under package.json)

Now let’s start with the usual express boilerplate code. Refer below if you want to

There are individual differences, obviously when compared with JavaScript. Let’s explore them one by one.

  • We no longer require the strict rule of using commonjs module system. ES6 imports are much welcome.
  • The variable PORT and the parameters _ and res have type assignments of number, Request, and Response respectively. Request and Response are express’ custom data types (interfaces to be accurate) which provide a blueprint of the necessary methods and properties.

Otherwise, this is precisely the same as we would type in Javascript.

Step 6: Bringing TypeScript in action

Welcome to the land of compilers. All we have to do is run the following scripts.

The server would start-up, resulting in the below output when launched in the browser.

Alt Text

What is unique here is that TypeScript compiles exactly to Javascript along with the folder structure. Say for example we had organized the models, routes, and controllers as separate directories. TypeScript intelligently looks for all the files inside those folders and replicates them into the outDir which we had specified in the config file.

Conclusion

That’s pretty much about it. Pretty easy, huh? Did that instigate you to use TypeScript more? It did for me, and I hope it works for you as well. If this procedure seemed a bit extensive or confusing, please do clone my repo and then analyze the file structure. I am sure that you will grasp it.

--

--

Sundeep Charan Ramkumar
UpSkillie

A MERN Stack developer who builds single page/Ecommerce applications for a living