Open In App

Node.js with TypeScript

Last Updated : 25 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

If you're immersed in the world of Node.js development, you're likely acquainted with the hurdles of handling and expanding a substantial codebase. A viable solution to tackle this is leveraging TypeScript, a statically-typed superset of JavaScript. TypeScript enriches the language with optional type annotations and sophisticated features.

Node.js: Node lets you run JavaScript on servers, which became really popular after it came out in 2011. But as your code gets bigger, JavaScript's flexible and loosely-typed nature can make things tricky. People who are used to other programming languages often find it hard because JavaScript isn't strongly typed. That's where TypeScript comes in – it adds stronger typing to JavaScript, making it easier to manage larger projects.

TypeScript: Think of TypeScript as an enhanced version of JavaScript. TypeScript is an open-source language maintained and developed by Microsoft. It adds extra features like strong typing (which is optional), compiling, and object-oriented programming. This makes it easier to handle big JavaScript projects. It's loved and used by a lot of software developers around the world.

Here are some benefits of using TypeScript

  • Optional static typing.
  • Type inference.
  • Compatibility with JavaScript.

By integrating TypeScript with Node.js, you enhance the development process, improving code readability and maintainability. While it doesn't directly impact runtime efficiency, TypeScript's static typing aids in early error detection, thereby simplifying the management of complex applications.

This tutorial guides you through creating a Node project with TypeScript. You'll construct an Express application employing TypeScript and then transpile it into JavaScript code.

Prerequisites

Steps to use Node.js with TypeScript

Step 1: Create a new project folder

Begin by creating a new folder for your project and then navigate to it using your terminal.

mkdir nodejs-express-ts
cd nodejs-express-ts

Now, utilize a text editor such as Visual Studio Code for writing and testing your code

Step 2: Initialize a new Node.js project

Now, open Visual Studio Code and launch the integrated terminal to initialize a Node.js project within your newly created folder and create a package.json file.

npm init -y

When initializing a package.json file in this manner, the --yes or -y flag utilizes the default settings configured by npm, bypassing the repeated questions asking for project details.

Step 3: Make a Simple Server with Express

After initializing the package.json file, add the Express packages to the project. In the terminal window, run the following command, where npm i is an alias to npm install:

npm i express

This command will install the latest version of the Express package in your folder.

Step 4: Install TypeScript

Install TypeScript as a development dependency:

npm i --save-dev typescript

The --save-dev option installs a package for development use only, not for running the app. It adds the package to the "devDependencies" section of your package.json file.

Step 5: Install @types/express @types/node

@types/express and @types/node are TypeScript declaration packages that provide type definitions for the Express framework and Node.js runtime, respectively.

npm install --save-dev @types/express @types/node

Now you have installed TypeScript, but you can't use it yet. To use TypeScript, you need to transpile your code to JavaScript. For this, you need a configuration file.

Step 6: Configure TypeScript

Create a configuration file for TypeScript.

npx tsc --init

This will create a tsconfig.json file in the root of your project directory. When you open the tsconfig.json file, you'll see many commented-out compiler options. The compilerOptions field is required and must be specified. Here's a summary of the default options inside the compilerOptions field:

  • target: es5
  • module: commonjs
  • strict: true
  • esModuleInterop: true
  • skipLibCheck: true
  • forceConsistentCasingInFileNames: true

Important options to enable are rootDir and outDir, which specify where the compiled files will go. Find these options in the tsconfig.json file and uncomment them.

By default, they are set to the project's root. Change them to build, as shown below:

{ 
"compilerOptions": {
...
"outDir": "build" ,
"rootDir": "src" ,
}
}

Here, src represents the source directory where your TypeScript files, such as app.ts or index.ts, are stored.

Step 7: Create an Express server with a .ts extension

Converting our JavaScript Express server to TypeScript is straightforward. Start by renaming the app.ts file in the src directory to app.ts. The .ts extension signifies a TypeScript file, which will be compiled to JavaScript during the application build process.

Next, open app.ts and make the following modifications to ensure TypeScript compatibility.

// src/app.ts

import express from 'express';
const app = express();
const port = 3000;
app.get('/', (req, res)=>
{
     res.send('Hello World');
});
 app.listen(port, ()=>{
     console.log(
`Connected successfully on port ${port}`)
});

So, our code is now valid TypeScript (.ts) code for Node.js, but we can't run it yet. First, we need to transpile the code.

Step 8: Building or Transpiling the TypeScript files

In a TypeScript project, transpiling or building involves the TypeScript Compiler (TSC) interpreting the tsconfig.json file to determine how to convert TypeScript files into valid JavaScript.

npx tsc

After running this command, a new directory called build will be created in the root of your project. Inside the build directory, an app.js file will be automatically generated.

directory-setup
The image shows a Node.js project using TypeScript, with a src folder for source files, a build folder for compiled code, and essential configuration files like tsconfig.json and package.json for efficient project setup and compilation.

Step 9: Run the Project

Running the project will start your project. This command executes the compiled JavaScript file and starts the server.

node build/app.js

You will see a message indicating that the server is running, along with a localhost address where you can access your application.

IMG_20240618_193147-(1)

Step 10: Testing Your Project with Postman

After setting up your application, you can use Postman to send requests to your server and test its responses. This step is crucial for ensuring your API works as expected.

IMG_20240618_193117-(1)
  • Open Postman: Launch the Postman application.
  • Create a New Request: Set up a new request in Postman with the GET method and the endpoint URL http://localhost:3000.
  • Send the Request: Click Send and view the response from your server.
  • Analyze the Response: Check the status code, response body, and headers to ensure your API is functioning correctly.

Conclusion

By following this tutorial, you've set up a Node.js project with TypeScript, creating a robust Express server. TypeScript's static typing helps catch errors early and improves code readability, making large projects easier to manage. You've also learned to configure TypeScript, transpile code, and test your API with Postman. Integrating TypeScript enhances your development workflow and prepares your application for future scaling and maintenance. This setup gives you a strong foundation for building robust and maintainable server-side applications.


Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg