Blog

How to Use TypeScript with NodeJS

by on March 26, 2019

Using NodeJS with TypeScript
The lion’s share of JavaScript developers prefer to use TypeScript in their projects as it helps avoid some problems at the assembly stage while still including many valuable features. Today we are going to share with you how to use the Backendless JS-SDK in conjunction with TypeScript in a project with a Node.js backend.

Backendless JS-SDK is a fully isomorphic library and it can be used in both a browser environment and a NodeJS backend environment and in most cases it also works well in other environments like React NativeAppcelerator, etc. The JS-SDK has been designed as a plain JavaScript library, but a few years ago we added types definitions for all methods and classes, so you can use the JS-SDK in your TypeScript projects without additional settings.

Create a Simple Web Server

At this stage, we will create a simple Node.js app. To do so, you must have Node.js installed on your machine; if you don’t have it yet, you can install the language from their official site at this link: https://nodejs.org.

Now, create a new directory and change the current directory in the terminal to the one we just created:

mkdir ./bl-app
cd ./bl-app

Next, let’s generate a package.json file by running the following command:

npm init

You will be asked a few questions about your project. You can simply keep everything set to the default value; a little bit later, we will modify the “scripts” section in the file.

Now that we can install modules from NPM, let’s install the express module:

npm i express -S

That’s enough for us to create a simple web server, so now let’s create a new JS file named ./src/app.js with the following content:

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

Run the server called node ./src/app and to check if everything works well, just open “http://localhost:3000” in your browser.

Setup Backendless

Make sure you have a Backendless developer account. If you don’t have one yet, you can register for a free account at https://develop.backendless.com.
Register for Backendless Developer Account
Create a new Backendless application. We will use the app for API calls.

Now let’s setup the Backendless JS-SDK and add logic for saving a new object in a Data Table. We will create/save a new object on each request from the client.

Install JS-SDK module from NPM:

npm i backendless -S

Replace the code in ./src/app.js with the following:

const express = require('express');
const Backendless = require('backendless');
const APP_ID = 'YOUR_APP_ID';
const API_KEY = 'YOUR_API_KEY';
Backendless.initApp(APP_ID, API_KEY);
class Person {
constructor(name) {
  this.name = name
}
}
function createPerson() {
const person = new Person('Bob');
return Backendless.Data.of(Person).save(person)
}
const app = express();
app.get('/', function (req, res, next) {
createPerson()
  .then(person => res.json(person))
  .catch(next)
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

Don’t forget to replace the APP_ID and API_KEY values with your own. You can find them in the Backendless Dev Console:
App ID and App Key in Backendless Console
After restarting the server, go to your browser and refresh the page where you have “http://localhost:3000” open. You will see that a new Person has been created:
Refresh browser to test function
Also, you can check in Backendless Dev Console to see that the data was added. To do so, go to Data Service and select the “Person” table in the left sidebar.
Confirm function worked in Backendless Console

Setup TypeScript

Now it’s time for the most important part of the article. Here we’ll show you how to add TypeScript to our Node.js project and how to use Backendless JS-SDK with TypeScript.

First, let’s install our dev dependencies by running the following command:

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

Now add a few npm commands to our package.json file:

"scripts": {
"tsc": "tsc",
"dev": "ts-node-dev --respawn --transpileOnly ./src/app.ts",
"prod": "tsc && node ./build/app.js"
},

To use TypeScript, we also need to have tsconfig.json. We can generate it with the following command:

npm run tsc — –init

This generates the tsconfig.json file with lots of options. I’ve removed all the commented lines to focus your attention on the active options, and I’ve also specified an output directory where our built files will be placed. When finished, my tsconfig.json file looks like:

{
"compilerOptions": {
  "target": "es5",
  "module": "commonjs",
  "outDir": "./build",
  "strict": true,
  "esModuleInterop": true
}
}

The last step before we can run our server is that we have to rename ./src/app.js to ./src/app.ts and rewrite our code using TypeScript.

import express from 'express';
import Backendless from 'backendless';
const APP_ID = 'YOUR_APP_ID';
const API_KEY = 'YOUR_API_KEY';
Backendless.initApp(APP_ID, API_KEY);
class Person {
  name: string;
  constructor(name: string) {
      this.name = name
  }
}
function createPerson(): Promise<Person> {
  const person = new Person('Bob');
  return Backendless.Data.of(Person).save<Person>(person)
}
const app: express.Application = express();
app.get('/', function (req, res, next) {
  createPerson()
      .then(person => res.json(person))
      .catch(next)
});
app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

Let’s check to see if it still works. Run the server npm run dev and open or refresh “http://localhost:3000” in your browser. One more thing, if you run npm run dev, you can modify your code and check how it works without restarting the server. Module ts-node-dev will do this for us. Let’s give it a try. Without stopping the server, change the Person class. For example, add a new property age:

class Person {
  name: string;
  age: number;
  constructor(name: string) {
      this.name = name;
      this.age = 12;
  }
}

Go to your browser and refresh the page to make a GET request to the server. You should see that we just created a person that has the property age.

Conclusion

As you can see, the Backendless JS-SDK is well adapted for use with TypeScript inside of a Node.js project. I hope you’ve found this article helpful! You can find the project what we built today on github.com.

Thanks for reading and see you soon.

Leave a Reply