DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Use TypeScript With Node.js

How to Use TypeScript With Node.js

In this post, we look at how TypeScript lovers can get this language running within their Node.js projects.

Vladimir Upirov user avatar by
Vladimir Upirov
·
Apr. 26, 19 · Tutorial
Like (2)
Save
Tweet
Share
16.64K Views

Join the DZone community and get the full member experience.

Join For Free

TypeScript and Node.js

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 is a fully isomorphic library and it can be used in both a browser environment and a Node.js backend environment and in most cases it also works well in other environments like React Native, Appcelerator, 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 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 names ./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.

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 the 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:

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:

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.

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. The ts-node-dev module 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 using 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 .

Thanks for reading and see you soon.

Node.js TypeScript

Published at DZone with permission of Vladimir Upirov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Using JSON Web Encryption (JWE)
  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • The 31 Flavors of Data Lineage and Why Vanilla Doesn’t Cut It
  • Three SQL Keywords in QuestDB for Finding Missing Data

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: