Typescript encounters an error when attempting to access a property of an undefined

Encountered a TypeError: Cannot read property 'ghNewPrMethod' of undefined

Every time I attempt to send a webhook POST to my Typescript application, the error mentioned above pops up.

Here is the snippet of code from the controller:

import { GhStatusSchema } from '../models/gh-status.model';
import { Request, Response } from 'express';

import * as crypto from 'crypto';
import { Helpers } from '../helpers';
import { GhNewPrMethod } from '../methods/gh-new-pr.method';

import { GitHubConfig } from '../../config/github';

const secret: string = GitHubConfig.secret;

export class GhNewPrController {
  public helpers: Helpers = new Helpers();
  public ghNewPrMethod = new GhNewPrMethod();

  public post(req: Request, res: Response) {
    console.log(111);
    this.ghNewPrMethod.slackMessage(req.body, req.get('x-github-delivery'))
  } 
}

it appears that there is an issue with this.ghNewPrMethod.slackMess and it seems like this is not defined properly.

** gh-new-pr.method.ts**

import * as Slack from 'slack-node';

import { GhMessageSchema } from '../models/gh-new-pr.model';
import { SlackConfig } from '../../config/slack';
import { UsersConfig } from '../../config/users';
import { Helpers } from '../helpers';

export class GhNewPrMethod {
  helpers: Helpers = new Helpers();

  public findSavedPR(id) {
    return new Promise((resolve, reject) => {
      GhMessageSchema.find({
        pull_request: id
      }, (err, message) => {
        if (err || message.length === 0) {
          reject(err);
        }
        resolve(message);
      });
    });
  }

  public slackMessage(payload, header) {
    console.log(payload);
  }
}

The reason for splitting the code into another file was to divide and conquer by breaking down the controller into smaller functions for reusability and cleaner code organization.

If anyone could provide some guidance or assistance on this matter, it would be greatly appreciated.

route.ts

import { Request, Response, NextFunction } from "express";
import { GhNewPrController } from '../controllers/gh-new-pr.controller';

export class Routes {

  public ghNewPrController: GhNewPrController = new GhNewPrController()

  public routes(app): void {

    app.route('/github')
      .post(this.ghNewPrController.post)

  }
}

Answer №1

If you're encountering a scoping issue, the solution is to utilize the bind function like this:

app.route('/github').post(this.ghNewPrController.post.bind(this.ghNewPrController))

According to developer.mozilla: "The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called."

Check out the DEMO here

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

Is it possible to integrate nedb with NativeScript?

I am currently developing an application that consists of a desktop app and a mobile app, both of which operate mostly in offline mode. For the desktop app, I have used Electron with nedb, angular2, and TypeScript. However, I am uncertain whether nedb can ...

Exploring the world of page jumps using Ionic3

I've created a tabs page with sections A, B, and C set up like this: tab1Root: any = HomePage; tab2Root: any = AboutPage; tab3Root: any = ContactPage; However, when I navigate from PageB to a new pageC, the URL changes to:http://localhost:8102/#/abo ...

Use RXJS to prevent having multiple nested subscriptions

I am looking to revamp the code snippet below: this.dataUserSubscription = this.store$.pipe(select(selectUser)).subscribe( user => { this.store$.pipe(select(selectUserData, {user}), take(1)) .subscribe(u ...

Asynchronous task within an if statement

After pressing a button, it triggers the check function, which then executes the isReady() function to perform operations and determine its truth value. During the evaluation process, the isReady() method may actually return false, yet display "Success" i ...

The EventEmitter in Angular 8 is prohibiting the emission of an Object

Is there a way I can emit an Object instead of primitive data types? I have an object const amount = { currenty: 'USD', total: '10.25' }; that I need to emit to the parent component. export class MyChildComponent implements OnInit { ...

Prime NG: Filtering options using label in dropdown menu

I'm facing an issue with my angular project that utilizes prime ng. The problem arises when attempting to perform a column search on rows of dropdown values. When searching for 'Jan', the system fails to retrieve any data, but interestingly ...

The dreaded error message [ERR_REQUIRE_ESM] has appeared, indicating that the require() function for an ES

I am currently developing a Discord bot using TypeScript and discord.js. However, when I attempted to compile the code this morning, I encountered the following error: C:\SECRET\Kostegator\dist\Util\getMeme.js:17 const node_fetch_1 ...

When building with Next.js, the React context (useContext) returns null, but functions properly when running in development mode

I am currently developing a Next.js app (App router) and utilizing a custom useLoading hook to manage the loading state across the application using a context provider. While everything functions perfectly in development mode (npm run dev), I encounter an ...

Utilize TypeScript to access scope within a directive

Is there a way to access the controller's scope properties using my custom TypeScript directive? For example, in this snippet below, I am trying to retrieve and log scope.message: /// <reference path="typings/angularjs/angular.d.ts" ...

import error causing an angular application to crash even with the module installed

Is there a possibility that an error is occurring with the import statement even though the syntax is correct and the required library has been installed? Could the issue lie within the core settings files, specifically the ones mentioned below (package.js ...

What is the process for incorporating a function into the prototype of an interface that functions as a class?

Adding a function to the prototype of a value is simple. For example: Array.prototype.removeAt = function (index) { if (index >= 0 && index < this.length) { this.splice(index, 1); } return this; }; declare global { export interfa ...

Vue 3 components array typified with Typescript

I'm attempting to establish an array of components representing various steps. Initially, I attempted to assign the type to these steps: const steps = ref<Component[]>([ Component1, Component2, Component3, ]); However, this approach is n ...

Using two separate ngModel directives in a parent component to control individual child component elements

One of the challenges I am facing is how to handle a child component with 2 input text-fields simultaneously. Both of these fields require ngModel validation in the parent component. Additionally, both inputs are mandatory and need to be checked using !for ...

What is the reason that the protected keyword is not retained for abstract properties in TypeScript?

I'm uncertain whether this issue in TypeScript is a bug or intended functionality. In my Angular project, I have 3 classes - an abstract service, a service that implements the abstract service, and a component that utilizes the implementing service. ...

Using a modal in a stack navigator with React Native in Expo

I'm facing an issue with stacknavigator in an expo app while trying to open a modal from it. When the modal is placed on the body of the app, everything works perfectly with no issues. However, if the modal is launched from a stack screen, most of th ...

Using Sigma.js in React with Typescript: A Comprehensive Guide

I'm attempting to set up a basic web application using React and TypeScript in order to experiment with Sigma.js graphs. However, I am facing issues as the end result does not display anything with Sigma. These are the steps I have taken: $ npx crea ...

Converting Abstract Type Members from Scala to TypeScript: A Handy Snippet

I have a brief example of a value level and type level list in Scala sealed trait RowSet { type Append[That <: RowSet] <: RowSet def with[That <: RowSet](that: That): Append[That] } object RowSet { case object Empty extends RowSet { t ...

A step-by-step guide on extracting information from a component and using it within a Guard

A challenge I am facing is how to display a warning prompt on the screen if the user tries to leave a page after making changes to a form. I have successfully created a Guard that logs a message to the console when the user attempts to navigate away from t ...

typescript add some flair to the setter function

I'm attempting to enhance a setter function within a class in the following manner: export class SearchResultSortBy{ private sortByChoice; constructor() { ...} /* getters & setters */ get sortBy() { return this.sortByCh ...

Generating a custom type in Typescript based on specific array keys

Imagine I have a structure like this: export interface MyObject { id: number title: string } and then I create an array as shown below: const myArray: MyObject[] = [ { id: 2358, title: 'Item 1' }, { id: 85373, title: &a ...