Nodejs with TypeScript

Learn via video courses
Topics Covered

Overview

TypeScript is an open-source language developed by Microsoft. Typescript is like an advanced version of javascript. TypeScript helps us to write clean, accurate, and effective code. Because TypeScript allows us to set the types and validate the type of values. Nodejs Typescript compiles the code and detects the error before execution. Hence, Typescript reduces the chance of runtime errors.

Pre-Requisites

  • Nodejs must be installed on your local development machine.
  • Good understanding of javascript, typescript, and their value types.
  • General understanding of linting, debugging, and deployment.

What is TypeScript?

In the above code, We declare two variables name and age in javascript. But javascript doesn't show any errors.

Because javascript dynamically assigned the type string to the variable name and age according to the value stored in these variables. But, We want age to be a number. Therefore, we use nodejs typescript to specify the type of the variable name and age as follows:

In the above code, We tried to assign a value of string type to age and the typescript showed the error

Therefore, Typescript set the type of variable and checks the type of value assigned to that variable. Typescript allows us to gain more control over javascript code. We use the extension .ts instead of .js. Every javascript code is a typescript code.

Learn about difference between typescript and javascript

Setting Up

Nodejs doesn't have built-in support for typescript. We will add the npm package typescript to add typescript compiler and @types/node to add type definition.

Typescript

  • Install the npm package typescript that helps to convert typescript to javascript anywhere on our development machine.
  • Check the installed version of typescript and verify whether typescript is installed or not.

Note: Sometimes tsc --version command doesn't work on windows. You can try to run the command tsc.cmd --version to check the typescript version.

Nodejs

  • Create a folder named nodejs-typescript and go to the current folder nodejs-typescript with CLI (Command Line Interface) as shown below.
  • Initialize the npm (Node package manager) to create a nodejs project.
  • Now, We will install the npm package @types/node and add a type checker for nodejs.
  • We need typescript dependencies to write rich code for the local development machine only.
  • We use the typescript compiler to convert typescript into javascript as the browser only understands javascript code.

Generating "tsconfig.json"

  • We will initialize the configuration file for nodejs typescript.
  • The above command will create a file named tsconfig.json inside the nodejs-typescript folder and add some code in JSON format.

Note: If the tsc --init command doesn't work, You can try to run the command tsc.cmd --init.

  • We will replace the existing code in the tsconfig.json file with the following code:
  • In the above code, We are using properties

    • target: It informs the typescript compiler about the JavaScript version we want after compilation. We will compile our code to javascript version "es2016".
    • module: The property module informs the typescript compiler about the module system for compiled javascript code. "module": "commonjs" instructs the typescript compiler to use the CommonJS module system.
    • rootDir: It specifies the directory where our source code exists. We are using the src folder to write the code.
    • outDir: After compilation, the Output javascript code will be stored in this directory. We are using the dist folder to store our compiled javascript code.
    • strict: It notifies the compiler whether to enable strict type-checking options or not. We set the property strict to boolean true.
    • exclude: It specifies the file that we do not want to compile. We are excluding the "./node_modules" folder.

Express Server With a ".ts" Extension

  • Install the following npm packages:

    • express: We will install express using npm install express --save to create server and routes.
    • @types/express: We will install a type checker for express using npm install @types/express --save-dev.
  • Create a new folder src, add a new file index.ts, and add the following code to the index.ts file.

  • In the above code, We are using:
    • import keyword to include express module with nodejs typescript.
    • listen() method of the express app to set the port 3000 on localhost.
    • get() method to send a response on URL https://localhost:3000/.
  • In the next section, We will compile the typescript file index.ts to javascript. Because nodejs only understand javascript and can not execute typescript.

Compiling TypeScript Files for Node.js

  • We will run the npm command to install typescript for the current nodejs project.
  • We will run the following command to convert the typescript of index.ts file into javascript.
  • npx tsc build javascript code and add it to the index.js file inside the dist folder. And folder structure looks like as shown below.
  • Now, We will execute the index.js file using the command

Output: TYPESCRIPT FOR NODEJS

Execute TypeScript Source Files Directly With ts-node

  • We do not want to run a command every time to build javascript and execute it for nodejs separately.
  • Hence, we use the npm package ts-node to execute the indes.ts file directly.
  • We will run the following command to install ts-node.
  • Now, We will run the command npx ts-node src/index.ts and it will produce the same output

EXECUTE TYPESCRIPT

TypeScript Integration With Third-party Node.js NPM Packages

Most npm packages are written in javascript and for nodejs. Therefore, We add npm packages for type support i.e. we used @types/node for nodejs and @types/express above in the other section of this article. Now, we will replace the code of the index.ts file with the following code.

  • In the above code, We are using Express, Request, and Response interfaces to check the value type of app, req, and res respectively.

ESLint Package to Lint TypeScript Code

  • We will run the following command to install the eslint package.
  • We use @typescript-eslint/parser to parse the format for typescript code and @typescript-eslint/eslint-plugin to add rules for typescript specifications. We will run the following command.
  • Now, create a file named .eslintrc.js inside the folder nodejs-typescript and add the following code:
  • Add the lint property in the scripts object to package.json.
  • Now, We will check the error for the index.ts file with the following command

Debugging TypeScript Source Files With Visual Studio Code

  • We will create a folder .vscode inside nodejs-typescript.
  • Create a launch.json file inside the ".vscode" folder and add the following code to the launch.json file
  • Press ctrl + shift + D and press the arrow icon on the left of the Debug index.ts tab.

DEBUG INDEX TAB

Deploying to Production

  • We can deploy a typescript project for production. But the browser doesn't understand typescript.
  • Therefore, We first compile the typescript using npx tsc and deploy compiled javascript build using the node command. We will add the build property to the script object.

TypeScript in the Node.js World

  • NestJS: It is a nodejs framework to build a javascript-based and a typescript-based server-side application.
  • TypeORM: It is an ORM (Object Relational Mapping) tool that supports multiple platforms.
  • Prisma: It is also ORM (Object Relational Mapping) tool that helps to manage queries for the database and to migrate the database.
  • RxJS: It is a javascript library that uses observables to work with asynchronous code and events.
  • AdonisJS: It is a backend framework that helps to build the backend without installing multiple npm packages
  • FoalTs: It is also a well-documented nodejs framework to build complete web applications.

Conclusion

  • Typescript enhances the readability and quality of the javascript. We can install typescript using npm install typescript -g.
  • npm package typescript helps to compile typescript into javascript.
  • We can directly execute a typescript file using npm packaged ts-node.
  • We can integrate typescript with third-party npm packages by adding their respective typescript definition starting with @types.
  • eslintrc.js file helps to add configuration, define rules, watch typescript files and detect issues.
  • We use the command npx eslint . to check errors for all javascript and typescript files in the root directory.
  • We use the command npx eslint . --ext ts to check errors only for typescript files
  • launch.json file and ctrl + shift + D is used to debug typescript files.
  • We can deploy a typescript project after compiling it into javascript with command npx tsc and serve the compiled javascript code with node command node dist/index.js.