A reference to 'this' is not permissible within a static function in Types

Based on this GitHub issue, it is stated that referencing this in a static context is allowed. However, when using a class structure like the following:

class ZController {
    static async b(req: RequestType, res: Response) {
            await this.a(req);
    }

    static async a(req) {
        console.log('here')
    }
}

An error occurs:

Error: unhandledRejection: Cannot read properties of undefined (reading 'a')
TypeError: Cannot read properties of undefined (reading 'a')
    at b (/usr/src/app/controllers/z.ts:24:33)
    at Layer.handle [as handle_request] (/usr/src/app/node_modules/express/lib/router/layer.js:95:5)
    at next (/usr/src/app/node_modules/express/lib/router/route.js:137:13)
    at xxx (/usr/src/app/middlewares/Auth.js:108:17)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

The project is utilizing Typescript version 4.4.2.

This raises the question - why does TypeScript not support this feature as expected?

Answer №1

In the code, there is an instance where an unbound copy of ZController.b is being passed. This results in this not being associated with ZController when it is called.

type Req = {};
type Res = {}
class ZController {
    static async b(req: Req, res: Res) {
        await this.a(req);
    }

    static async a(req: Req) {
        console.log('here')
    }
}

ZController.b({}, {}); // functions correctly

const zb = ZController.b; // zb does not have a binding to `ZController`

zb({}, {}); // at this point, we encounter an issue as 'this' is undefined

// solution by re-binding back to ZController

const zb2 = ZController.b.bind(ZController);

zb2({}, {}); // works correctly

// alternative by creating a wrapper:

const zb3 = (req: Req, res: Res) => ZController.b(req, res);

zb3({}, {}); // operates smoothly

Alternatively, avoid using this in static methods:

class ZController2 {
    static async b(req: Req, res: Res) {
        await ZController2.a(req);
    }

    static async a(req: Req) {
        console.log('here2')
    }
}

const zb4 = ZController2.b;

zb4({},{}) // executes without issues

Playground Link

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 name 'const' is missing or not found

While working on my Angular application, I attempted to utilize the Typescript 3.4 feature known as "const assertion" in the following manner: const counterSettingsDefaults = { setTo: 10, tickSpeed: 200, increment: 1 } as const; Unfortunately, this resul ...

What is the best way to sort through an Array of photo filenames?

I have a list of image names that contain UUIDs. images [ "auditid_626_UUID_666666_time__1582577405550.jpg", "auditid_626_UUID_999999_time__1582577405554.jpg", "auditid_626_UUID_999999_time__1582577405557.jpg" ] These ima ...

Navigation arrows for sliding`

Is there a way to add custom right/left arrows to the Ionic slider component? Demo: Check it out on Stackblitz Note: Make sure to refer to the home.html page for more details. https://i.sstatic.net/jQ62l.png .html <ion-slides [pager]="true" [slide ...

The recursive component is functional exclusively outside of its own scope

I'm facing an issue where my recursive component is not nesting itself properly. The problem arises when I try to use the Recursive component inside another Recursive component. Although the root is correctly inserted into the Recursive component fro ...

The exportAs property for matAutocomplete has not been specified

Issue Detected An error occurred with the directive "exportAs" set to "matAutocomplete" ("-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto"> I implemented code referenced from https://material.angular.io/components/auto ...

Restricting number input value in Vue using TypeScript

I have a component that looks like this: <input class="number-input py-1 primary--text font-weight-regular" :ref="'number-input-' + title" @keypress="onKeyPressed" :disabled="disabled& ...

Having constant problems with ngModel twoway binding. Any suggestions on how to successfully bind to a property in order to update an api link?

I am attempting to implement two-way binding in order to dynamically change the API endpoint when a button is clicked. The value attribute of the button should be used as part of the API URL string. I tried following an example in the Hero Angular App, bu ...

Calculating the percentage difference between two dates to accurately represent timeline chart bar data

I am in the process of creating a unique horizontal timeline chart that visually represents the time span of milestones based on their start and finish dates. Each bar on the timeline corresponds to a milestone, and each rectangle behind the bars signifies ...

How come TypeScript tuples support the array.push method?

In the TypeScript code snippet below, I have specified the role to be of Tuple type, meaning only 2 values of a specified type should be allowed in the role array. Despite this, I am still able to push a new item into the array. Why is the TS compiler not ...

Struggling to convert a JSON response into an object model using TypeScript in Angular?

I'm encountering a problem when trying to convert a JSON response into an object. All the properties of my object are being treated as strings, is that normal? Below is my AJAX request: public fetchSingle = (keys: any[]): Observable<Medal> =&g ...

Error: TypeScript React SFC encountering issues with children props typing

I am currently working with a stateless functional component that is defined as follows: import { SFC } from "react"; type ProfileTabContentProps = { selected: boolean; }; const ProfileTabContent: SFC<ProfileTabContentProps> = ({ selected, child ...

Having trouble retrieving the Ionic 2 slides instance - getting a result of undefined

As I attempt to utilize the slides and access the instance in order to use the slideto functionality programmatically, I find myself encountering the issue of receiving 'undefined' back despite following the documentation. Here is my TypeScript ...

What happens when i18next's fallbackLng takes precedence over changeLanguage?

I am currently developing a Node.js app with support for multi-language functionality based on the URL query string. I have implemented the i18next module in my project. Below is a snippet from my main index.ts file: ... import i18next from 'i18next& ...

Exploring ways to interact with an API using arrays through interfaces in Angular CLI

I am currently utilizing Angular 7 and I have a REST API that provides the following data: {"Plate":"MIN123","Certifications":[{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"preventive","StartDate":"06 ...

Adjust the selected value in real-time using TypeScript

Hey there, I've got a piece of code that needs some tweaking: <div> <div *ngIf="!showInfo"> <div> <br> <table style="border: 0px; display: table; margin-right: auto; margin-left: auto; width: 155%;"& ...

Show a notification pop-up when a observable encounters an error in an IONIC 3 app connected to an ASP.NET

Currently, I am in the process of developing an IONIC 3 application that consumes Asp.NET web API services. For authentication purposes, I have implemented Token based auth. When a user enters valid credentials, they receive a token which is then stored in ...

The function cloneElement does not share any properties with the type Partial<P> and Attributes

I'm encountering a perplexing issue with my code. When I attempt to call cloneElement with the second parameter being of type Type { foo: number } has no properties in common with type 'Partial<Child> & Attributes', TypeScript thro ...

Issue with InversifyJS @multiInject: receiving an error stating "ServiceIdentifier has an ambiguous match"

Having an issue with inversifyJs while trying to implement dependency injection in my TypeScript project. Specifically, when using the @multiInject decorator, I keep receiving the error "Ambiguous match found for serviceIdentifier". I've been referenc ...

What is the best way to retrieve matching values based on IDs from an imported table?

How can I retrieve values that match on ID with another imported table? My goal is to import bank details from another table using the ID and display it alongside the companyName that shares the same ID with the bank details. I've attempted several o ...

The server response value is not appearing in Angular 5

It appears that my client is unable to capture the response data from the server and display it. Below is the code for my component: export class MyComponent implements OnInit { data: string; constructor(private myService: MyService) {} ngOnInit ...