In this article we will learn how can we build a NodeJS and express application using TypeScript, which is being treated as a JavaScript replacement and many NodeJS applications have already started shifting their code from JavaScript to TypeScript. So its just a matter of time for TypeScript to become the de facto standard for building NodeJS applications.

Also checkout this article to learn how to Implement CRUD in NodeJS with Express and MongoDB.

Prerequisites

Following are the things you will need before starting this tutorial

  • Visual Studio Code and NodeJs, installed on your system
  • basic understanding of NodeJs and Express

What is TypeScript?

TypeScript is JavaScript with syntax for types. TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.

https://www.typescriptlang.org/

Typescript is a superset of JavaScript, which means it includes everything which JavaScript includes with some additional features on top, like static type checking, which is like when we define a variable we can tell what sort values it can hold for example a string or a number or boolean. Same goes for functions we can define what sort of values function will accept and what will be the return type. This is the main feature of this language and hence the name TypeScript.

TypeScript also helps in identifying errors and bugs during compilation and before code runtime like it can alert you to misspelled properties and functions, detect passing the wrong number of arguments and the wrong types of arguments to functions. TypeScript can also provide smarter autocomplete suggestions. This helps in speeding up the development process especially when we are building a big application involving a large codebase.

Where as in JavaScript we have to use external tools like ESLint and extensive test cases to cover the same thing.

Hence typescript adds an extra safety and enhances productivity

If you already know JavaScript, then there is no learning curve to know TypeScript, just a little bit of added features.

Getting started with TypeScript

To get started, first we need to install it, use below command to install TypeScript globally in your system

npm install -g typescript

After running this command we get access to tsc command which runs typescript compiler, run the below command to check the version of TypeScript installed in your system.

tsc --version

Now let’s start writing some TypeScript code, create a file named index.ts with following code inside

//index.ts file

const greeting : string = 'Hello World!!'
console.log(greeting)

Here we can see, we are using static type to define greeting. Now this typescript code cannot run anywhere, like in browser or NodeJS, so what we do is convert this typescript code to JavaScript code using typescript compiler. So we run the below command

tsc index.ts

Now this command will create index.js file in the same directory containing the following code, which we can run in our browser or node.

//index.js file

var greeting = 'Hello World!!';
console.log(greeting);

Here we see that we get equivalent JavaScript code for our typescript. We also notice that the types are gone. One more thing to note is, here we have var instead of const, thats because, typescript compiler by default is using es5 instead of es6. But we can change this behaviour with the help of tsconfig.json file.

Creating a Typescript config file

We can use the below command to generate tsconfig.json file

tsc --init

Now you will get tsconfig.json file in your root folder, which will contain some values in it, most of which will be commented. We don’t have to worry about each and every option listed in the file, but only few.

First will be changing the target. By default we will have es2016 as value for target, we can change it to ESNext, which will let the typescript compiler to compile the code to the latest flavour of JavaScript.

Let’s give it a try, after changing it and hitting tsc command to recompile the code, we should see the below code in index.js file.

//index.js file

"use strict";

const greeting = 'Hello World!!';
console.log(greeting);

As we can see, var is changed to const, as the compiler is now using latest flavour of JavaScript which is ES2022.

Using watch flag

Now to avoid using tsc command to recompile our typescript code every time we make a change, we can use the following command which will constantly watch our ts file for changes and compile it automatically.

tsc index.ts --watch

On running the command, you should see following in your terminal

using typescript compiler

This command will also show any errors in our code in real time as follows.

using typescript compiler with error
Using ts-node package to compile TypeScript

Now it is sort of annoying, in order check our typescript code output we should first compile it to JavaScript and then run that JavaScript file. To avoid this step we can make use of a package called ts-node. Let’s install it using the below command

npm install -g ts-node

After installing ts-node, we can now execute our typescript code using the below command

ts-node

This command does not create any js file in our root directory as well.

Building NodeJS Express App with TypeScript

Now that we have covered the basics of typescript, let’s start building a NodeJS and express application.

Let’s initialize a NodeJS application using the below command

npm init

This will create a package.json file in project folder.

Bootstrapping the application

Let’s also create tsconfig.json file, just like we did above. In addition to changing the target value to ESNext, we will also uncomment and make the following changes

{
  "compilerOptions": {
    "target": "ESNext",            /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations.
    "rootDir": "./src",            /* Specify the root folder within your source files. */                        
    "outDir": "./build",             /* Specify an output folder for all emitted files. */
    "moduleResolution": "node",    /* Specify how TypeScript looks up a file from a given module specifier. */
  }
}

Here we are specifying where our ts files will sit in “rootDir” and where should compiler store the js files which will be “outDir” value. Rest all values we can leave as it is.

let’s start by installing the following dev dependencies

npm i -d typescript nodemon express

here we will use nodemon to constantly look for changes in our files and automatically start the server.

Note: we can also use ts-node-dev instead of nodemon, and use the command “ts-node-dev –respawn ./src/app.ts” which will serve the same function as nodemon.

Using Typescript with packages

To get access to type definitions for any package we have the following command

npm i @types/<packagename>

Not all packages will have @types. We can identify if a package has type definitions with the following @types tag.

express type tag

We should now install type definitions for node and express using the below command

npm i -d @types/node @types/express
Adding start, dev and build scripts

Also let’s add the following scripts in package.json file

{
  "scripts": {
    "start": "node build/app.js",
    "dev": "nodemon src/app.ts",
    "build": "tsc -p ."
  }
}

Here we have defined three scripts, first one is start script which will run our built JavaScript file, next is dev script which we will use in development to run the server using nodemon and build script to compile typescript code to JavaScript.

Now our package.json file looks like as follows

{
  "name": "typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node build/app.js",
    "dev": "nodemon src/app.ts",
    "build": "tsc -p .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^18.6.2",
    "ts-node": "^10.9.1",
    "typescript": "^4.7.4"
  }
}

With this we are done with our configurations and setup.

Building Express app with typescript

Let’s now create a new app.ts file in src folder with the following code.

// src/app.ts file

import express, {Application, Request, Response, NextFunction} from 'express'

const app : Application= express();

app.use('/', (req: Request, res: Response, next : NextFunction) => {
    res.send('Hello from express')
})

app.listen(8000,()=>{
    console.log('listening to requests on port 8000')
})

Here we have coded a simple express server. You will notice that how we are using types here for different express objects. Also here we can import syntax instead of require to add dependencies into a file.

Now to run this in development, as we have defined dev script, we can use the following command

npm run dev

We should see the following result in terminal

terminal screenshot

and in browser we will get the below result

express-hello

Now we can build our code using the below script

terminal build

Now when we do this, as we have defined “outDir” value as “./build” in tsconfig.json, we will get a build folder created with app.js file inside as shown below

ap.js file

As we can see we have our app.js file compiled. Now we can execute this build file with our start script as shown below

build test

Here we see we get the same result as we did while executing the typescript server code and when we go to the browser we will get same result as we did above.

This completes our implementation of using TypeScript in NodeJS Express app.

Summary

In this article we just covered the very basics of getting started with typescript as a backend developer. We learned what is typescript and how can we use it to build NodeJS and express application. We learned how we can configure typescript using tsconfig.json file and different ways to compile and run it in NodeJS.

You can also checkout full source for this implementation here.

Leave a Reply

Your email address will not be published. Required fields are marked *