How TypeScript can be used with Node and Express?

At the onset of my career, I embraced strong-typed languages as a web developer. However, the allure of JavaScript and Python’s dynamic features captivated me. The flexibility of not declaring variables enhanced my productivity and fueled my passion. Initially skeptical about TypeScript, a pivotal shift occurred in my mindset.

What prompted this change?

I adopted a strategic approach—opting for simpler languages like JavaScript for solo projects, reserving TypeScript for team collaborations and large-scale endeavors. In this article, I delve into the rationale behind this decision.

TypeScript

TypeScript is a statically typed superset of JavaScript that enhances the language with optional static typing. It enables developers to catch errors during development, offers better tooling support, and facilitates the creation of more maintainable and scalable code. TypeScript code is transpiled to standard JavaScript, ensuring compatibility with existing JavaScript frameworks and environments. Overall, TypeScript combines the flexibility of JavaScript with the benefits of static typing, providing a robust solution for modern software development.

If you’re unfamiliar with TypeScript, I highly recommend perusing the following overview to gain insights into this statically typed superset of JavaScript.

https://www.tutorialspoint.com/typescript/typescript_overview.htm

and view the following: https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

Comparison of Productivity and Maintenance

Typescript is an object oriented language used for app development. This means that the setup of project is remunerated with the maintenance of large scale projects. Lets see why it is so:

type safe= less errors

When we define the type in our code we allow the IDE to find out the errors and bugs while using the functions and classes that would be viewed by us at runtime.

Example:

function add (a: number , b: number):
number { return a+b;}
let mySum: number;
mySum=add(1,"two");
let myText: String;
myText=add(1,2);

I have used visual studio code and there is an error i.e “Two”

on line 4: error as string parameter is passed to a function that can only accept number

on line 6: error as assign to a string , the output gives a number .

these two errors would have gone unnoticed without typescript, showing bugs at runtime.

Project Modules exposed by IDE

There are hundreds of classes which are scattered across different files. When we declare types the IDE finds the origin files and relate the objects with them.

Full-Stack Developer - javascript Developer
Full Stack Sofware Developer

Programmers face difficulty in maintaining this language that is why they avoid transferring from java and C# to js but typescript helps in overcoming this obstacle.

Setting up express project with Typescript

lets see the steps taken to set up project in Express.js project :

npm init

install typescript package

npm install typescript -s

Typescript node package

Typescript cant be run in node.js engine rather it only runs java script. The node typescript package is used as transpiler for .ts files to .js scripts. Babel is used as typescript for trans-piling. however the market standard is to use Microsoft package for this purpose. The script tsc is put inside the package.json :

“scripts”: {
“tsc”: “tsc”
},

 

This can be used to call typescript functions by using command line. below command is used:

npm run tsc — –init

this help in initializing the typescript by creating the file tsconfig.json . In this file we will remove comment i.e  outDiroption and choose transpile location to deliever .js files :

Full Stack Sofware Developer.,Full Stack Aws Serverless Application Developer., Full-Stack Developer.,Javascript Developer.,typescript with node and express

Express.js installation

npm install express -s

As typescript dont know express class type so express and typescript are independent. A special npm package can be used to recognize express class:

npm install @types/express -s

HELLO WORLD

Below is an example:

https://expressjs.com/pt-br/starter/hello-world.html

var express=require( 'express' ) ; 
 var app = express(); 
app.get( '/'function (req,res){
res . send( 'Hello World! ' ) ;
});
 app.1isten(3000, function ( )
 { 
console. log( ' Example app listening on port 3000! ')
});

now create folder app and inside it create file app.ts using following code:

// lib/app.ts
import express = require('express');

// Create a new express application instance
const app: express.Application = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

COMPILATION OF FIRST APPLICATION

npm run tsc

this command creates a build folder and .js file:

Full Stack Sofware Developer.,Full Stack Aws Serverless Application Developer., Full-Stack Developer.,Javascript Developer.,typescript with node and express

Running EXPRESS

node build/app.js

on port 3000 we can see our output:

Full Stack Sofware Developer.,Full Stack Aws Serverless Application Developer., Full-Stack Developer.,Javascript Developer.,typescript with node and express

Transcript running by not using transpiling

TypeScript can run directly on Node.js through the ts-node package, primarily employed during development. However, for ultimate deployment or integration, JavaScript code is utilized. The ts-node package is an integral part of another package, tts-node-dev, and is activated post-installation. Upon installing ts-node-dev, server restart commands ensure real-time updates whenever changes occur in the original project files.

npm install ts-node-dev -s

some more scripts are added in package.json:

“scripts”: {
“tsc”: “tsc”,
“dev”: “ts-node-dev –respawn –transpileOnly ./app/app.ts”,
“prod”: “tsc && node ./build/app.js”
},

start dev environment :

npm run dev

run server :

npm run prod


In Conclusion,

TypeScript emerges as a powerful ally in the development journey. Its static typing enhances code reliability during development, while the versatility to seamlessly transition to JavaScript for deployment adds practicality. The utilization of tools like ts-node and ts-node-dev brings efficiency to the development process, enabling dynamic adaptation to file changes. Embracing TypeScript not only fosters a robust development environment but also contributes to building scalable and maintainable software solutions.

Visited 1 times, 1 visit(s) today

Leave a comment

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