An extremely popular JavaScript superset, TypeScript, is gaining immense popularity among software developers. Wondering why? TypeScript incorporates every JavaScript feature and functionality with additional properties like type-checking and static typing. As per the 6sense report, the United States is the top geography using TypeScript for programming language with a sizable number of 44.64%.
Now, talking about Node.js, multiple factors make Node.js a very prominent JavaScript framework. It has a robust NPM (Node Package Manager) environment that offers open-source code that you can utilize in any of your projects with the help of NodeJS development services. Node.js is one of the greatest platforms for building server-side apps, however, it does miss some modern elements such as type-checking. A Node.js codebase is also a bit complex to manage. On the other hand, Typescript supports all the modern coding patterns.
But what if we use them together?
I bet the tech geek inside you would be looking for an answer. Well, the answer is YES! Node.js and TypeScript (working together) have been getting full limelight among the developers over these years. Why? As TypeScript helps in the development process, it also ensures that your software solution is free of any vulnerabilities, bugs, and teeny tiny errors, whereas Node.js is a server-side, open-source execution platform for JavaScript code. But – why use TypeScript with Node.js? and how to use TypeScript with Node.js.
Don’t stress! This tutorial will help you understand why to use TypeScript and JavaScript together and how to use TypeScript with Node.js.
Let’s start!
What is TypeScript?
TypeScript is an object-oriented, tightly typed, and open-source programming language and a superset of JavaScript. TypeScript code is changed to JavaScript, which can be used in any environment supporting JavaScript, such as Node.js or your apps. Overall, TypeScript is a better version of JavaScript with some additional features and functionalities. TypeScript also expands JavaScript with additional syntax to deliver a better robust interface with the editor you’re using.
What is Node.js?
Node.js is a server-side, open-source execution platform for JavaScript code. It is majorly used to develop real-time applications like chats, web push notifications, news feeds, chats, and web push because it enables a lasting association from the browser to the server. Node.js is also an asynchronous event-driven JavaScript runtime for developing extensible network apps.
Even though Node.js is remarkable for building server-side apps, it does lack modern features such as type-checking. There are certain times when it gets challenging for Node.js development services to manage a Node.js codebase. This is where Typescript supports all the present coding techniques, such as type checking and static typing. This is the reason why you should have Typescript as the main language for managing Node.js capabilities are the best option.
Completing the ‘what’ part, let’s move to the ‘why’ part. In the following section, we’ll discuss why it’s important to use TypeScript with Node.js.
Benefits of Using TypeScript with Node.js
Following are some of the significant reasons why you need to use TypeScript with Node.js:
- Predictable – When considering TypeScript, there is complete certainty that everything you define stays exact. For example, if you declare any variable as a Boolean, it will never change to a string en route.
- Optional Static Typing – TypeScript provides optional static typing, which means that when you declare a variable, it will never alter its type and only use specific values.
- Support Major IDEs – You can work with TypeScript in most Integrated development environments (IDEs). Most of these IDEs offer syntax highlighting and code completion.
- Early Verification of Bugs – With the help of TypeScript you can easily discover most of the type errors, making their production low. This minimizes the time software developers and engineers spend testing the code in later phases.
- Utilize Existing Packages – One of the best advantages of using TypeScript with Node.js is there’s no need to build everything from the ground up; you can easily utilize existing NPM packages. Moreover, TypeScript sustains a strong community that manages and builds type definitions for significant packages.
- Seamless Code Refactoring – You can easily refactor or modify your TypeScript application without altering its behavior. Moreover, the existence of navigation tools and the understanding of your code by IDE (Integrated Development Environment) makes it seamless for code refactoring effortlessly.
Here comes the heart and soul of the article – how to use TypeScript with Node.js?
How to Use TypeScript with Node.js?
Let’s see the prerequisites first:
- Node.js – Node.js is a cross-platform run-time environment that enables running JavaScript code external to a browser environment. You can also check if the node installation is already done on your machine with the help of this command;
node -v
If not, you can then download Node.js from its authentic website. After the installation, run the above-mentioned command again to check whether the configuration is done properly.
- A Node Package Manager – Here, you can either use NPM or Yarn. The installation of NPM takes place by default as soon as you install Node.js. Here, I’ll be using NPM as a package manager in this article. Hence, use this command to check the version;
npm –v
Let’s now install TypeScript with Node.js
Step 1: Setup your project folder
We will begin by building a project folder for the TypeScript project. You can name the folder according to your choice. Following are the commands to start;
mkdir typescript-node
cd typescript-node
Step 2: Initialize the project
Use NPM to initialize your project using the following command;
npm init -y
The above command then creates a package.json file. The -y flag in the command tells us about npm to include defaults. The generated file will deliver an exact 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”
}
TypeScript with Node.js Configuration
Step 1: Install the TypeScript compiler
Now install the TypeScript compiler for your project. Run the following command;
npm install –save-dev typescript
The output on your command line will be something same as this;
added 1 package, and audited 2 packages in 26s
found 0 vulnerabilities
Important Note: The above technique installs TypeScript locally on the project folder you are operating on. You can now install TypeScript globally on your system, you aren’t required to install it every time you work on any project. Hence, use this command to install TypeScript globally;
npm install -g typescript
You can now check if TypeScript has been installed utilizing this command;
tsc -v
Step 2: Add Ambient Node.js types for TypeScript
TypeScript consists of multiple types, including, Implicit, Explicit, and Ambient. You always need to add Ambient types to the global execution scope. Use the following command to add Ambient Types;
npm install @types/node –save-dev
Step 3: Create a tsconfig.json file
This is the configuration file that defines all the TypeScript compile options. Run the following command that comes with multiple compile options defined;
npx tsc –init –rootDir src –outDir build \
–esModuleInterop –resolveJsonModule –lib es6 \
–module commonjs –allowJs true –noImplicitAny true
Here’s the output on the terminal;
The tsconfig.json file, which consists of some defaults and comments, will be generated.
This is what we have configured:
- The rootDir is where TypeScript will look forward to the code. Now, you’ve to direct it to /src folder where you write the code.
- The outDir folder defines where to put the compiled code. Configuration of this code stores in build/ folder.
Using TypeScript with Node.js
Step 1: Create src folder and index.ts file
Now we can see the basic configuration. You can now develop a basic TypeScript app and compile it. The file extension for a TypeScript file is .ts. Run the following commands while inside the folder you created in the previous steps;
mkdir src
touch src/index.ts
Step 2: Add code to the TypeScript file (index.ts)
You can begin with something simple like;
console.log(‘Hello world!’)
Step 3: Compile TypeScript code to JavaScript code
Run the following command;
npx tsc
You can check the build folder (build/index.js), and see that an index.js has been generated with this output;
Hence, TypeScript has been compiled into JavaScript code.
Step 4: Run the compiled JavaScript code
Always remember that TypeScript code cannot run on browsers. Thus, you need to run the code in index.js in the build folder. Run the following command;
node build/index.js
This will be the output;
Step 5: Configure TypeScript to auto-compile to JavaScript code
Compiling TypeScript code manually whenever you modify your TypeScript files can waste your time. You can install ts-node, which runs TypeScript code directly without waiting for the compilation, and nodemon, which 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”
}
You 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 like this one;
Wrapping Up!
In this article, we learn why and how to use TypeScript with Node.js. Here we discussed the technical parts like – installation of TypeScript with Node.js, configuring a Node.js project with TypeScript support, and finally using TypeScript with Node.js. However, integrating TypeScript with Node.js sometimes can get quite overwhelming and confusing, especially if you’re a newbie and just entered the tech world.
But there’s nothing to worry about. I have the best solution!
So, to go through with the entire process of TypeScript with Node.js, you can opt for the best web app development services to make all your work easy and seamless.
That’s all from my end.
Hope you find the article helpful. Thank you for your time and patient reading.
Happy Learning!
Author details:
Author Name- Mr. Pratik Mistry
Author bio–
I am Pratik Mistry, a rare mix of technologist and Executive Vice President in sales at Radixweb. My passion lies in helping companies to grow revenues by delivering top notch custom software development solutions and build value-based partnerships. When not driving high-impact go to market strategies, I love to try new cuisines and going to the movies.
Social network:
LinkedIn: https://www.linkedin.com/in/pratikradixweb/
Twitter: https://twitter.com/pratikjmistry
Profile Picture: