DEV Community

Cover image for Getting Started Using TypeScript with Node.js and Express
Pankaj Kumar
Pankaj Kumar

Posted on

Getting Started Using TypeScript with Node.js and Express

In this article, I am going to explain the typescript with nodejs and express.

Setup new project:

npm init

Install typescript package

Node.js engine runs Javascript and not Typescript. The node Typescript package allows you to transpile your .ts files to .js scripts. Babel can also be used to transpile Typescript, however, the market standard is to use the official Microsoft package.

npm install typescript

Update package.json file by adding ‘tsc’ in scripts tag to call typescript functions from the command line.

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

Now run below command:

npm run tsc — — init

This command initializes the typescript project by creating the tsconfig.json file.
Install Express

npm install express @types/express

By default Typescript does not “know” types of Express classes. There is a specific npm package for the Typescript to recognize the Express types.
Create Server.js file(server/server.js)

import express = require(‘express’);
// Create a new express app instance
const app: express.Application = express();
app.get(‘/’, function (req, res) {
res.send(‘Hello World!’);
});
app.listen(3000, function () {
console.log(‘App is listening on port 3000!’);
});

Compile the above code by running below command:

npm run tsc

After running above command a new file is created in server folder named server.js(Mainly Ts code is converted in Js)
Run the app:

node server/server.js

Check on the browser on URL: http://localhost3000

GitHub Link: https://github.com/pankajkrr/nodejs-express-ts

I hope this article will remove the fear of TypeScript to get started in Node.js Express Application.
Thanks!

Top comments (0)