A TypeScript class method that returns a different function

I have created a class with the following implementation:

import {Request, Response, Router} from 'express';
import {IAccessTokenMiddleWare} from "./IAccessTokenMiddleWare";

class AccessTokenMiddleWare implements IAccessTokenMiddleWare {


    private jwtToken: string;
    constructor() {

        this.jwtToken = "";
    }
    public init()  : any  {

        return function (req: Request, res: Response, next: any) {

            this.addJwtToReqBody(req);
        }
    }

    private addJwtToReqBody(req) {

        console.log("ADDED...")
    }
}

export {AccessTokenMiddleWare}

I am initializing it in my code as shown below:

var accessTokenMiddleWare = new AccessTokenMiddleWare();
router.use(accessTokenMiddleWare.init());

However, I'm encountering an error message:

error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.

Could someone guide me on resolving this error?

Answer №1

In Typescript (and JavaScript), functions do not have a fixed context for 'this', as it is determined by the caller. This means that when you return a function, it can be invoked with any object serving as 'this'. By default, the compiler assumes 'this' to be any, which can lead to errors if using 'strict':

accessTokenMiddleWare.init().call({ newThis: true });

If you want to capture the correct context within the declaring class, use an arrow function to explicitly define 'this' as the current class:

class AccessTokenMiddleWare implements IAccessTokenMiddleWare {


    private jwtToken: string;
    constructor() {

        this.jwtToken = "";
    }
    public init() {

        return (req: Request, res: Response, next: any) => {

            this.addJwtToReqBody(req);
        }
    }

    private addJwtToReqBody(req: Request) {

        console.log("ADDED...")
    }
}

Also note that I removed the type annotation from the 'init' method so that the compiler can infer that the return will be a function, providing better type checking. You can also manually specify the return type like this:

init(): (req: Request, res: Response, next: any) => void

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

Ways to adjust .keyup based on the presence of a variable

I am currently in the process of constructing a search form that utilizes an ajax function within .keyup, which may have various arguments. I aim to determine if a specific argument should be included based on the presence of another value. Here is my curr ...

Enhancing the elements in a current array of arrays

I am in the process of creating an array structured like this var qwe = [[a,b],[c],[d]], where a and b serve as identifiers. The values for a - d are being extracted from the DOM. Currently, my JavaScript code is functioning as intended, but I aim to merg ...

Connection between Mongodb and nodejs fails when trying to connect to the localhost server

I have been attempting to connect my local mongo server through nodejs but encountering some difficulties. Although I followed the simple tutorial provided by official mongodb, the connection does not seem to hook properly with the once part. var mongoose ...

What is the process for consumers to provide constructor parameters in Angular 2?

Is it possible to modify the field of a component instance? Let's consider an example in test.component.ts: @Component({ selector: 'test', }) export class TestComponent { @Input() temp; temp2; constructor(arg) { ...

Is there a distinction between copying an array [...arr] and referencing the original array arr in JavaScript ES6?

Imagine a situation where you need to loop through a constant array. Is there a distinction between [...arr].forEach((elem) => { // your operations }); and arr.forEach((elem) => { // your operations }); Are these two methods interchangeabl ...

Strategies for managing the fallback scenario while utilizing 'createReducer' to generate a reducer and 'on' to manage actions

In the past, our reducers were created like this before the createReducer helper method was introduced: export function reducer(state: AppState, action: Action) { switch (action.type) { case "[Category List] Add Category": return { . ...

I am experiencing difficulty in retrieving the result for the following code snippet

I'm currently attempting to retrieve data for my chart from a data.csv file. <!DOCTYPE html> <html> <head> <title>D3 test</title> <style> .grid .tick { ...

Steps to avoid IE11 prompt (Do you really want to leave this site)

In the midst of making a webpage, I find myself faced with the peculiar issue of only having a dropdown to select. To make matters worse, when attempting to navigate to the next page in IE11, a pesky message pops up. Curious about the default behavior of ...

Ways to make an element disappear when clicking outside of it in Angular 7 or with CSS

After entering text into an input field and pressing the space key, a div called 'showit' will be displayed. However, I want this div to hide when clicking outside of it. See the code below for reference: home.component.html <input type="tex ...

Is there a way to deactivate dates that are more than 14 days ahead of the current date in Vue Datepicker?

Although I've seen similar inquiries, none of them address my specific issue. I am working with a Vue.js datepicker and I want to restrict the user from selecting a date that is less than 2 weeks ahead of the current date. Essentially, I need all date ...

Tips for Displaying Label Names in Dashboard Charts

Can anyone provide guidance on displaying category names in a chart? To see the relevant code snippet, check row 92 where categories are fetched from an API and connected to products. I am trying to understand how to retrieve data based on category nam ...

Upon clicking, the reset function will be triggered

I have a jQuery code that includes a click event on td elements. After clicking on a td, an input field with text appears and the focus is set at the end of the text. However, I want to remove the focus after the initial click so that I can click in the ...

What is the process for importing components from a Stencil library into a React application?

After successfully creating: a stencilJS component library named "my-lib" using the "npm init stencil" wizard and an Ionic React app using "ionic start myApp tabs" I am now trying to incorporate the default "my-component," aka MyComponent from my-lib. H ...

Sending NodeJS Buffer as form data to Spring Boot in a correct way

I'm facing an issue with my NodeJS application where I am working with an image buffer called qrCode const qrCodeData = Buffer.from(body).toString('base64'); //body received, not sure if base64 is correct f ...

initiate scanning for HTTP GET calls

My current project involves using electron to create an application that serves multiple image files through a webserver using express. Another app built for Android is responsible for retrieving and posting files to this server. While I have successfully ...

Tips for customizing the main select all checkbox in Material-UI React data grid

Utilizing a data grid with multiple selection in Material UI React, I have styled the headings with a dark background color and light text color. To maintain consistency, I also want to apply the same styling to the select all checkbox at the top. Althou ...

Using Google Apps Script to input data into the next available row

Utilizing Google Apps Script, I am retrieving data from another spreadsheet and storing it daily in a sheet named "DATABASE". Although my current solution is basic, it keeps overwriting existing data. I wish to enhance the script to copy data from the imp ...

Is there a way to set an image as the background of my HTML screen?

{% extends "layout.html" %} {% block app_content %} <div> {% from "_formhelpers.html" import render_field %} <form method="post" enctype="multipart/form-data"> <div class = "container"> < ...

Camera Capacitor designed to eliminate popup notifications

I am utilizing Angular along with the camera plugin in Capacitor to locally save images on both desktop and tablets. I aim to utilize the CameraSource to directly access the camera or open the gallery for files without displaying a prompt. This is how my ...

Decoupling DAOs from controllers to enhance reusability

My goal is to display a list of categories in various views, such as listing them out or loading them as options in a product creation form. To achieve reusability, I need to separate the Data Access Object (DAO) from the controllers. The main challenge li ...