TypeScript is paving its way as one of the most popular programming languages for modern organizations. 

TypeScript is a compiled, strictly-typed JavaScript superscript (built on top of JavaScript language). This statically typed language, developed and maintained by Microsoft, supports object-oriented concepts like its subset, JavaScript. 

This open-source programming language has many use cases, such as creating web, large-scale, and mobile applications. TypeScript can be used for frontend and backend development. It also has various frameworks and libraries that simplify development and extend its use cases. 

Why use TypeScript with Node.js? This article will discuss why TypeScript is considered “better” than JavaScript, how to install it using Node.js, configure and create a small program using TypeScript and Node.js. 

TypeScript with Node.js: Benefits

  • Optional static typing: JavaScript is dynamically typed, meaning a variable’s data type is determined at runtime and not during compile time. On the other hand, TypeScript offers optional static typing, meaning that once you declare a variable, it won’t change its type and will only take certain values. 
  • Predictability: When dealing with TypeScript, there is assurance that everything you define will remain the same. For instance, if you declare a certain variable as a Boolean, it can never change to a string along the way. As a developer, you are assured that your functions will remain the same. 
  • Easy to spot bugs early: TypeScript detects most type errors early, so their likelihood of moving to production is low. This reduces the time engineers spend testing code in later stages. 
  • Supported on most IDEs: TypeScript works with most Integrated development environments (IDEs). Most of these IDEs provide code completion and syntax highlighting. This article will use Visual Studio Code, another Microsoft product. 
  • Easy to refactor code: You can update or refactor your TypeScript app without changing its behavior. The presence of navigation tools and the IDE understanding your code makes it easy to refactor the codebase effortlessly. 
  • Utilizes existing packages: You don’t have to create everything from scratch; you can use existing NPM packages with TypeScript. This language also has a strong community that maintains and creates type definitions for popular packages. 

How to use TypeScript with Node.js

Even though TypeScript has these advantages, modern browsers can’t read its code in plain form. Therefore, TypeScript code must be first transpiled to JavaScript code to run on browsers. The resulting code will have the same functionality as the original TypeScript code and extra functionalities unavailable in JavaScript. 

Prerequisites 

  • Node.js: Node is a cross-platform run-time environment that allows running JavaScript code outside a browser environment. You can check if the node is installed on your machine using this command;

node -v

Otherwise, you can download Node.js from the official website. Run the above command again after installation to check whether it has been configured well. 

  • A Node Package Manager: You can use NPM or Yarn. The former is installed by default when you install Node.js. We will use NPM as a package manager in this article. Use this command to check its current version;

npm -v

Installing TypeScript with Node.js

Step 1: Setup a project folder

We will start by creating a project folder for the TypeScript project. You can give this folder any name of your liking. You can use these commands to get started;

mkdir typescript-node

cd typescript-node

Step 2: Initialize the project

Use npm to initialize your project using this command;

npm init -y

The above command will create a package.json file. The -y flag in the command tells npm to include defaults. The generated file will have a similar output. 

{

  "name": "typescript-node",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "test": "echo "Error: no test specified" && exit 1"

  },

  "keywords": [],

  "author": "",

  "license": "ISC"

}

Configuring TypeScript with Node.js

Step 1: Install the TypeScript compiler

You can now install the TypeScript compiler to your project. Run this command;

npm install --save-dev typescript

The output on your command line will be something similar to this;

added 1 package, and audited 2 packages in 26s

found 0 vulnerabilities

Note: The above approach installs TypeScript locally on the project folder you are working on. You can install TypeScript globally on your system, so you don’t have to install it every time you work on a project. Use this command to install TypeScript globally;

npm install -g typescript

You can check if TypeScript has been installed using this command;

tsc -v

Step 2: Add Ambient Node.js types for TypeScript

TypeScript has different types, such as Implicit, Explicit, and Ambient. Ambient types are always added to the global execution scope. Use this command to add Ambient Types;

npm install @types/node --save-dev

Step 3: Create a tsconfig.json file

This is the configuration file that specifies all the TypeScript compile options. Run this command that comes with several compile options defined; 

npx tsc --init --rootDir src --outDir build 

--esModuleInterop --resolveJsonModule --lib es6 

--module commonjs --allowJs true --noImplicitAny true

This will be output on the terminal;

<img alt="image-237" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/image-237.png" data- decoding="async" height="359" src="data:image/svg xml,” width=”1183″>

The tsconfig.json file, which contains some defaults and comments, will be generated.

<img alt="image-238" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/image-238.png" data- decoding="async" height="419" src="data:image/svg xml,” width=”984″>
tsconfig.json file

This is what we have configured:

  • The rootDir is where TypeScript will look for our code. We have directed it to /src folder where we will write our code. 
  • The outDir folder defines where the compiled code is put. Such code is configured to be stored in build/ folder.

Using TypeScript with Node.js

Step 1: Create src folder and index.ts file

Now we have the basic configuration. We can now create a simple TypeScript app and compile it. The file extension for a TypeScript file is .ts. Run these commands while inside the folder we created in the previous steps;

mkdir src

touch src/index.ts

Step 2: Add code to the TypeScript file (index.ts)

You can start with something simple like;

console.log('Hello world!')

Step 3: Compile TypeScript code to JavaScript code

Run this command;

npx tsc

You can check the build folder (build/index.js), and you will see that an index.js has been generated with this output;

<img alt="image-243" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/image-243.png641acf9e9d51e.jpg" data- decoding="async" height="219" src="data:image/svg xml,” width=”1017″>

TypeScript has been compiled into JavaScript code. 

Step 4: Run the compiled JavaScript code

Remember that TypeScript code cannot run on browsers. We will thus run the code in index.js in the build folder. Run this command;

node build/index.js

This will be the output;

<img alt="image-242" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/image-242.png641acf9ea9c96.jpg" data- decoding="async" height="125" src="data:image/svg xml,” width=”1059″>

Step 5: Configure TypeScript to auto-compile to JavaScript code

Compiling TypeScript code manually whenever you change your TypeScript files can waste time. You can install ts-node (runs TypeScript code directly without waiting to be compiled) and nodemon (checks your code for changes and automatically restarts the server). 

Run this command;

npm install --save-dev ts-node nodemon

You can then go to the package.json file and add this script;

"scripts": {

   "start": "ts-node ./src/index.ts"

}

We can use a new code block for demonstration purposes;

function sum (num1:number, num2:number, num3:number){

    return num1   num2  num3;

}

console.log(sum(10,15,30))

Delete the index.js file (/build/index.js) and run npm start. 

Your output will be similar to this one;

<img alt="image-241" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/image-241.png641acf9eb606a.jpg" data- decoding="async" height="657" src="data:image/svg xml,” width=”1056″>
sum of 3 numbers

Configure TypeScript Linting with eslint

Step 1: Install eslint

Linting can be useful if you want to maintain code consistency and catch errors before runtime. Install eslint using this command;

npm install --save-dev eslint

Step 2: Initialize eslint

You can initialize eslint using this command;

npx eslint --init

The initialization process will take you through several steps. Use the following screenshot to guide you through;

<img alt="image-240" data- data-src="https://kirelos.com/wp-content/uploads/2023/03/echo/image-240.png641acf9ec555f.jpg" data- decoding="async" height="513" src="data:image/svg xml,” width=”1379″>

Once the process is over, you will see a file named .eslintrc.js with contents similar to this;

module.exports = {

  env: {

    browser: true,

    es2021: true

  },

  extends: 'standard-with-typescript',

  overrides: [

  ],

  parserOptions: {

    ecmaVersion: 'latest',

    sourceType: 'module'

  },

  rules: {

  }

}

Step 3: Run eslint

Run this command to check and lint all the files with the .ts extension;

npx eslint . --ext .ts

Step 4: Update package.json 

Add a lint script on this file for automatic linting. 

"scripts": {

    "lint": "eslint . --ext .ts",

  },

TypeScript with Node.js: Best practices

  • Keep TypeScript up-to-date: TypeScript developers are always releasing new versions. Ensure you have the latest version installed on your machine/ project folder and benefit from new features and bug fixes. 
  • Enable strict mode: You can catch the common programming errors at compile time when you enable strict mode on the tsconfig.json file. This will reduce your debugging time, leading to more productivity. 
  • Enable strict null checks: You can catch all the null and undefined errors at compile time by enabling strict null checks on the tsconfig.json file. 
  • Use a code editor that supports TypeScript: Loads of code editors exist. A good practice is to pick code editors such as VS Code, Sublime Text, or Atom that support TypeScript through plugins. 
  • Use types and interfaces: With types and interfaces, you can define custom types you can reuse in your entire project. Such an approach will make your code more modular and easy to maintain. 

Wrapping Up

You now have the basic structure of an app created with TypeScript on Node.js. You can now use the regular Node.js packages but still, write your code in TypeScript and enjoy all the extra features that come with the latter. 

If you are just getting started on TypeScript, ensure you understand the differences between TypeScript and JavaScript