Kiren S
Kiren S

Reputation: 3097

Typescript Member Function returning another Function

I have a class

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 invoking it like below

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

Getting the error

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

How can I solve this error?

Upvotes: 1

Views: 178

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250106

Functions in Typescript (and JavaScript) do not have a fixed this, so this is determined by the caller. The function you return could be invoked with any this object, and so the compiler assumes this to be any by default, leading to an error if you use strict:

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

If you want to capture this from the declaring context you should use an arrow function that will type 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...")
    }
}

Note I also removed the type annotation from init you can let the copiler infer that the return will be a function and get better type checking. You could also specify it manually : init(): (req: Request, res: Response, next: any) => void

Upvotes: 3

Related Questions