9

I have a simple auth middleware for express. It checks header and if all cool it calls next()

Now when i am in "DoSomething" "this" is equal to global and not the instance of "Test" and "this.DoSomeThingPrivate" is undefined.

I have tried the

DoSomeThingPrivate :() => void;

this.DoSomeThingPrivate = () => {
...
}

pattern. But also does not work.

import express = require('express');

var app = express();

class Test {    
    constructor() {        
    }

    DoSomething(req:express.Request, res:express.Response, next:Function) :void {       
        this.DoSomeThingPrivate();
    }

    private DoSomeThingPrivate() :void
    {       
    }
}

var test = new Test();

app.use(test.DoSomething);

Relates to this

Any Ideas...

thanks

2 Answers 2

21

The following should work fine i.e. use fat arrow for DoSomething not DoSomethingPrivate:

import * as express from 'express';

var app = express();

class Test {    
    constructor() {        
    }

    // important: 
    DoSomething = (req:express.Request, res:express.Response, next:express.NextFunction) => {       
        this.DoSomeThingPrivate();
    }

    private DoSomeThingPrivate() :void
    {       
    }
}

var test = new Test();

app.use(test.DoSomething);

Note: You should not need to use bind. Also https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1

Sign up to request clarification or add additional context in comments.

3 Comments

you can also use type express.NextFunction for next param.
I think this approach is considerably better thant bind.
You can let the compiler infer the parameters types by typing DoSomething like so: DoSomething: express.RequestHandler = (req, res, next) => ...
10

You've passed a reference just to the function itself. The function's instance will be global. You need to bind the function to the instance of test.

app.use(test.DoSomething.bind(test));

4 Comments

thanks dude that worked. I am still getting use to typescript
No worries. That's not a Typescript specific problem though. You'll find that happens generally in JavaScript.
In addition to this answer and @basarat's answer, here's [a great description of 'this' in TypeScript][1] which describes the cause of the problem, the solutions offered here and the tradeoffs when choosing one of them. [1]: github.com/Microsoft/TypeScript/wiki/…
An important argument for the double fat arrow syntax DoSomething = (...params...) => { ...function contents...} versus .bind is that double arrow is typesafe in TypeScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.