What could be causing the TypeScript class property to be undefined?

Below is the code snippet I am working with:

class FeedbackController {

  public homePage(req, res){
    this.test();
    res.send('Welcome to feedback service');
  }
 
  private test(){
    console.log('test called');
  }
}

export default new FeedbackController();

This is how I am calling it in my project:

import FeedbackController from '../controller/feedbackController';

    const routes = (app) => {
        app.route('/')
        .get(FeedbackController.homePage);

    };

    export default routes;

However, I encountered the following error:

TypeError: Cannot read property 'test' of undefined

I'm unsure about what is causing this issue. Can someone help me figure out what's wrong?

Answer №1

This is more of a JavaScript issue than TypeScript. To understand how this functions in JS, refer to this link.

To solve the problem, you can replace routes with:

.get((req, res) => FeedbackController.homePage(req, res))

or

.get(FeedbackController.homePage.bind(FeedbackController))

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

Exploring Substrings in TypeScript strings

Can you pass a partial string (substring) as a value to a function in TypeScript? Is something like this allowed? function transform( str: Substring<'Hello world'> ) { // ... } If I call the function, can I pass a substring of that st ...

Implementing serialization and deserialization functionality in Typescript for classes containing nested maps

I am currently facing a challenge in transforming Typescript code into NodeJS, specifically dealing with classes that contain Map fields of objects. I have been experimenting with the class-transformer package for serialization and deserialization (to JSON ...

Typescript: Utilizing a generic array with varying arguments

Imagine a scenario where a function is called in the following manner: func([ {object: object1, key: someKeyOfObject1}, {object: object2, key: someKeyOfObject2} ]) This function works with an array. The requirement is to ensure that the key field co ...

No results returned by Mongoose/MongoDB GeoJSON query

I have a Schema (Tour) which includes a GeoJSON Point type property called location. location: { type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true ...

Contrast the different characteristics of string dynamic arrays in Angular 6

I am working with two arrays of strings. One array is a dynamic list of checkboxes and the other is the source to check if the item exists in the first array. I need to implement this dynamically using Angular 6, can you help me with this? Currently, the ...

Update the TypeScript definitions in the index.d.ts file using the npm command, by overriding it with the reference types

After running npm install, I noticed that the index.d.ts file contains a reference to the wrong path: /// <reference types="[WrongPath]"/>. As someone new to npm, TypeScript, and web development in general, I'm wondering if it's possible t ...

Is there a way to dynamically retrieve a JSON element in Typescript?

I am using a data grid throughout my application, and currently, I am retrieving the selected rowid with the following code. Here is the HTML snippet: <tbody> <tr *ngFor="let ddata of tableData.data; let i = index" (click)="setClickedRow(ddat ...

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...

Consolidate various arrays of objects while eliminating duplicate items based on an optional property

Imagine having multiple arrays like these: const arr1 = [ { "id": "1", "type": "sales" }, { "id": "2", "type": "finance" } ] const arr2 = [ { "type": "s ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

Stop the MatSort feature from activating when the space key is pressed in Angular Material

I am currently using angular material tables and have implemented filters for each column. The filter inputs are located in the row header of each column, which is working fine. However, I am facing an issue where whenever I type and press the space key, ...

What could be causing Next.js to re-render the entire page unnecessarily?

As a newcomer to Next.js, I am trying to develop an app where the header/navbar remains fixed at all times. Essentially, when the user navigates to different pages, only the main content should update without refreshing the navbar. Below is the code I have ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

The function you are trying to call is not valid... the specified type does not have any call signatures [ts 2349

Having some trouble using functions from Observable Plot example with a marimekko chart in my TypeScript project. I encountered an error on this particular line: setXz(I.map((i) => sum.get(X[i]))) The code snippet causing the issue is as follows: fu ...

A guide on using sinon to stub express middleware in a typescript project

I'm currently facing a challenge in writing an integration test for my express router using typescript, mocha, sinon, and chai-http. The router incorporates a custom middleware I created to validate JWT tokens present in the header. My goal is to moc ...

The provided Material-UI Fade component contains multiple children, which is not supported by 'ReactElement<any, any> | undefined'

I'm struggling to implement a Material UI <Fade> component in my code. Unfortunately, I keep encountering the following error message and as someone who is still learning TypeScript, I am unsure of how to resolve it. Error: Expected ReactElement ...

What is the reason for the inability of `Array<Value>, Value` to properly retrieve the type of the array value?

I am encountering an issue with the type declaration below: function eachr<Subject extends Array<Value>, Value>( subject: Subject, callback: ( this: Subject, value: Value, key: number, subject: Subject ...

Tips on excluding node_modules from typescript in Next.js 13

I am constructing a website in the next 13 versions with TypeScript, using the src folder and app directory. When I execute `npm run dev`, everything functions correctly. However, upon building, I encounter this error... ./node_modules/next-auth/src/core/l ...

Creating Beautiful MDX Layouts with Chakra UI

Currently, I am attempting to customize markdown files using Chakra UI within a next.js application. To achieve this, I have crafted the subsequent MDXComponents.tsx file: import { chakra } from "@chakra-ui/react" const MDXComponents = { p: (p ...

What are some ways to implement Material UI's Chip array to function similar to an Angular Chip Input?

Can the sleek design of Angular Material's Chip input be replicated using a React Material UI Chip array? I am attempting to achieve the modern aesthetic of Angular Material Chip input within React. While the Material UI Chip array appears to be the ...