Can you explain the difference between a public app and express.Application?

As I delved into the world of TypeScript and Node, I stumbled upon a perplexing line of code:

  public app: express.Application;

This line is nested within the context of an import statement and a class definition. Let's take a closer look at it:

import express, { Request, Response } from "express";
import bodyParser from "body-parser";

class App {

  constructor() {
    this.app = express();
    this.config();
    this.routes();
  }

  //TODO: What is public app: express.Application
  public app: express.Application;

  private config(): void {
    this.app.use(bodyParser.json());
    this.app.use(bodyParser.urlencoded({ extended: false }));
  }

  private routes(): void {
    const router = express.Router();
    router.get('/', (req: Request, res: Response) => {
      res.status(200).send({
        message: 'Hello World!'
      })
    });
    router.post('/', (req: Request, res: Response) => {
      const data = req.body;
      // query a database and save data
      res.status(200).send(data);
    });
    this.app.use('/', router)
  }
}

const app = new App().app;
const port = 4040;

app.listen(port, function() {
  console.log('Express server listening on port ' + port);
});

The usage of `public app: express.Application;` has left me puzzled. I am seeking clarity on its purpose and significance in this code snippet. Can someone shed some light on this for me?

Answer №1

Initially, it's worth mentioning that the term public isn't a reserved word in TypeScript but rather a syntax used in JavaScript classes.

In TypeScript, the syntax begins with the symbol :, followed by a type declaration - which can take various forms such as TypeScript interface, data type, or object; for instance, within an attribute labeled Application in a module named express.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The process of computing and graphing an array based on a specific field

After creating a straightforward mongoose query to extract an array of data and sorting it, I received the following response: [ { _id: 60c3dce8f27cc56bbcf20e94, steamID: '76561199105033642', displayName: 'username', L ...

Creating a 10-digit unique value can be achieved with either meteor or JavaScript

I am in need of generating 10 character unique codes, containing both letters and digits, to be utilized for system generated gift vouchers. Currently, the code I am using includes 13 numbers. var today = new Date(); Number(today); Is there a different m ...

Next.js is throwing an error: "Module cannot be found: Unable to resolve 'canvg'"

I am facing an issue in my next.js project where I keep encountering the following error message: error - ./node_modules/jspdf/dist/jspdf.es.min.js:458:25 Module not found: Can't resolve 'canvg' I'm confused because I have not included ...

What could be causing the "10 $digest error" to appear in my code?

My goal was to create a basic app that could detect the size of the browser and display it. But, I encountered an error message saying "Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!" app.controller('AppCtrl',function($win ...

Is it possible to have setTimeOut() executed after the page has been redirected?

Why is it not possible to duplicate: The question was not addressed in the previous post. I have a link for deletion, which, when clicked, triggers a popup with a button. Upon clicking that button, the page inside the popup redirects to a new internal pag ...

Working with JavaScript Arrays within a JSON file data

I am currently learning React and attempting to display random images from the Picsum website using their API. The JSON file I receive contains various information, but I am specifically interested in extracting the image URLs. Although it appears that my ...

Trigger Angular2 EventEmitter in child component to inform parent component

I am having trouble triggering an event from the child component to the parent component. @Component({ template:'<foo></foo>' }) export class ParentComponent{ onDoSomething($event){ //handling logic goes here } } @Compo ...

How to retrieve a single user using server-side props in Next.js

I'm currently building a dashboard using nextjs and implementing authentication with next-auth. However, I've encountered an issue when trying to display individual user data upon login to the dashboard. It seems that I am unable to retrieve the ...

How can you display a loading indicator after a delay using Observables, but make sure to cancel it if the loading is completed

Within my customer-detail component, I have implemented code that achieves the desired outcome. However, I believe there might be a more reactive and observable way to approach this task. Instead of using an if statement to set this.isLoading = true;, is ...

I am puzzled by the behavior of the $.getJSON request. I am uncertain about how to properly format the request with the callback=? parameter

Out of the three jQuery JSON requests, one is encountering cross-domain errors due to my lack of understanding how to include the callback=? parameter (or the reason why it signifies JSON vs JSONP). I am working on two requests to the same API; however, o ...

The data in local storage does not align with the handleChange event

One scenario that I encountered involved using a select element to choose languages. Initially, when the value or code from the select language is obtained, it is saved in local storage. Subsequently, this stored language code is used as a parameter in an ...

Take two inputs, divide them, and then multiply the result by 100

I am currently troubleshooting the total project match function, as it is not working properly. I aim to have this function divide the first function by the second function and then multiply the result by 100. Here is a snippet of my code: matchContribu ...

Tips for creating an effective dark mode toggle switch on a website

I was experimenting with creating a dark-mode switch for a website, but I'm not convinced that my implementation is the most efficient. Essentially, I ended up duplicating each file and adding a "2" at the end to create modified versions for each sect ...

Adjust the appearance of an element in a different parent when hovering over a specific element with a matching index

I have implemented a menu on my site in two different ways - one using text and the other using pictures. Users can click on both types of menus. Now, I am looking to create an interactive feature where hovering over a specific item in the text menu (such ...

A React component that exclusively renders component tags

After successfully loading index.html with no JavaScript errors, I ran into an issue where nothing was rendering on the page. Upon inspecting the webpage, all I could see was a tag and nothing else. It turns out that I have a component called "list". The ...

Is it feasible to switch the classList of a form element that also has an event listener attached to it?

While I don't have a specific code snippet to share, I did have an idea and attempted to implement it. Unfortunately, it didn't yield the desired results. const validateEmailAddress = function (e) { const regex = /^[a-zA-Z0-9.!#$%&&apos ...

What is causing the error to occur during the installation of the NestJS Client?

Encountered an error while attempting to install the nestjs client, and I'm completely puzzled by this issue. PS C:\Users\meuser> npm i -g @nestjs/cli npm ERR! code ETARGET npm ERR! notarget No matching version found for @angular- ...

Switch out the URL in npm's build process

While developing, I am using a mock REST service but for the public release, I intend to switch to a real backend. Is there a method to update the endpoint URL during the npm build process? ...

Update the class name by utilizing template literals

I'm currently in the process of mastering template literals as I have a project where I need to utilize them. However, I seem to be encountering an issue that I can't quite figure out. Here is the code that is currently working: const classes = ...

An unusual problem encountered while working with NextJS and NextAuth

In my NextJS authentication setup, I am using a custom token provider/service as outlined in this guide. The code structure is as follows: async function refreshAccessToken(authToken: AuthToken) { try { const tokenResponse = await AuthApi.refre ...