Telerik blogs
How ToT2 Dark_1200x303

In this post, we will be building a simple Node.js application and then migrating it into a TypeScript app.

JavaScript

JavaScript is a scripting language native to the web used to make web apps interactive. It is usually used to add logic to markup (HTML) and stylesheets (CSS) in web development. JavaScript is what makes a web page user-interactive instead of being plain and static—it opens up a way for users to engage with web apps. It is very popular and is used to build web applications, both on the client-side and the server-side too, like when building server applications using Node.

TypeScript

TypeScript is a compiled language that is object-oriented, strongly typed and made by the team at Microsoft. It is considered a superset of JavaScript, supporting other JavaScript libraries like Angular, and is very portable for various browsers, operating systems and even devices.

JavaScript vs. TypeScript

JavaScript has a few limitations when you think about building a scalable server-side application. When JavaScript was built, the primary aim was client-side web development and not server-side. However, with the emergence of Node.js, more people started to use it for the server-side and that began to reveal these limitations. Some things like object-oriented programming (OOP), type-checking and compile-time error checks made it not so easy for JavaScript to be a great choice for server applications and so TypeScript was built to solve that.

JavaScript still remains a scripting language, while TypeScript is an OOP language. TypeScript also has features like interfaces and support for modules that JavaScript does not. JavaScript is an interpreted language, which means that the web browser interprets it, but TypeScript is a compiled language and so it always compiles JavaScript.

What We Are Building

In this post, we will be building our very first JavaScript application, and then after it works, we will convert it to TypeScript. This will best illustrate the idea of migrating from JavaScript to TypeScript for beginners.

Setting Up Node.js

The first thing to do is to install Node.js if you do not already have it installed. Node.js basically helps us execute our JavaScript files.

node.js download screenshot

Head over to Node.js and download it for your machine, extract the file and install it. You can check if you already have Node installed by opening your terminal and running the command below:

node -v

If you see a version response, then you have Node already installed on your PC.

Creating Files

The next thing to do is to create a new folder in any chosen directory on your PC and then open it up in your code editor. I use and recommend VS Code, which you can get here. Create a new file, call it server.js and copy the code block below into it:

var http = require('http');
function onRequest(req, res){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello there world!');
  res.end();
}
http.createServer(onRequest).listen(8000);

This basically creates an HTTP variable that connects with your browser, then creates a server with the onRequest function and listens on port 8000 to provide the response, which is just plain text saying hello world.

Now open the terminal inside your VS Code app and run the command below:

node server.js

Open up any of your browsers to localhost:8000, and you will see that the hello world message is displayed as expected.

Message says  ‘Hello there world!’

Project Manifest

Just like every JavaScript framework you must have heard about like Angular, there is always a manifest file that shows your configurations and serves as a kind of manual for how to navigate, test, and build your Node projects. It is usually in a JSON format, the file is popularly named package.json and we can create it easily ourselves. Create a new file and call it package.json and inside of it, copy the code block below:

{
"name": "nodeapp",
"version": "1.0.0",
"description": "a test node application",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "Lotanna Nwose",
"license": "ISC"
}

You can also achieve this easily by running the command:

npm init

That will bring up a wizard that would take you through creating this exact file.

Using Express

Node.js has a couple of frameworks too that make running JavaScript even much easier so you do not have to know all of these commands we just saw. Using Express begins with just installing it:

npm install express

Now create a new file and call it index.js and then inside of it, paste in the code block below:

const express = require('express');
const app = express();
app.get('/',(req, res, next) => {
    res.send('hello there world!')
});
app.listen('8000', () => {
    console.log('Server is on');
});

With Express, we use the app to send our request and to listen on the port too. This gives us the exact same result and abstracts a lot more. Now that we have the hello world app set, let’s migrate the same project to TypeScript.

Converting to TypeScript

The first thing to note is that TypeScript compiles back to JavaScript as we already discussed. Now, to install TypeScript, you can do that in your terminal:

npx typescript — - init

In the tsconfig file generated, make sure these options are uncommented:

“moduleResolution”: “node”
“rootDir”:./src”
“outDir”:./dist”

Next thing is to create a folder, call it src and move the index.js file into it.

Then install TypeScript as a dev dependency—you can do that with this command:

npm i -D typescript @types/node @types/express

Now your package.json file should look like this:

{
  "name": "nodeapp",
  "version": "1.0.0",
  "description": "a test node application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node dist/index.js"
    "build": "tsc -p tsconfig.json"
  },
  "author": "Lotanna Nwose",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^16.11.10",
    "typescript": "^4.5.2"
  }
}

We also added a build command to compile the TypeScript into JavaScript code in the dist folder.

The next to do is to rename the index.js file to index.ts. Immediately you will see red lines everywhere, indicating some things that work in JavaScript that will not be permitted in TypeScript.

TypeScript Is JavaScript

Without changing any major thing in the code, we can use the JavaScript right inside a TS file.

const express = require('express');
const app = express();
app.get('/',(req:any, res:any, next:any) => {
    res.send('hello there world!')
});
app.listen('8000', () => {
    console.log('Server is on');
});

Let’s build it to show this:

npm run build
npm run start

You will see that a dist folder has been created with a newly compiled index.js file, and the second command runs it to show it works as expected.

Refactoring the Code

Now TypeScript has a few new rules like everything should have a type and modules should be imported rather than using the required function. Let’s effect some of this in our code.

Firstly, we can change the require to something modular, a TypeScript best practice, changing this:

const express = require('express');

to something like:

import express, { Request, Response, NextFunction } from 'express'

Then the second thing we do is to change the type of the arguments we have in our get function from:

app.get('/',(req, res, next) => {
    res.send('hello there world!')
});

to something like this:

app.get(/,(req:Request, res:Response, next:NextFunction) => {
 res.send(‘hello there world!)
});

This is how to do the conversion—you can learn more about using TypeScript through the official documentation here. You will see a lot of similarities with JavaScript and the motivation for TypeScript as you go.

Wrapping Up

In today’s post, we took a look at JavaScript and TypeScript as beginners and how to migrate a simple JavaScript application to a TypeScript one in a few steps. We also looked at how different both languages are and how we can start refactoring them. Happy hacking!


5E9A474B-EBDB-439E-8A4A-3B041B0BEDA6
About the Author

Nwose Lotanna Victor

Nwose Lotanna Victor is a web technology enthusiast who documents his learning process with technical articles and tutorials. He is a freelance frontend web developer based in Lagos, Nigeria. Passionate about inclusion, community-building and movies in Africa, he enjoys learning new things and traveling.

Related Posts

Comments

Comments are disabled in preview mode.