0

I am creating an object (a dummy http response object) as illustrated below:

res = {
    body : '',
    write : (text : string) => {
        this.body = this.body + text;
    },
    end : () => {}
};

But the typescript compiler is giving error:

error TS2108: 'this' cannot be referenced within module bodies.

I know this is possible (to have this inside object) in javascript, how to accomplish this in typescript?

2 Answers 2

3

You can accomplish it by changing the arrow function write to standard function, then it will work as usually in plain JavaScript.

res = {
    body : '',
    write : function(text: string) {
        this.body = this.body + text;
    },
    end : () => {}
};

This is because of how arrow functions change how this work within them. It is well described here.

Standard functions (ie. written using function keyword) will dynamically bind this depending on execution context (just like in JavaScript), arrow functions on the other hand will preserve this of enclosing context. This is a conscious design decision as arrow functions in ECMAScript 6 are meant to address some problems associated with dynamically bound this (eg. using function invocation pattern).

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

Comments

0

Before David submitted the (correct) answer, I managed to come up with a work-around. It doesn't answer my own question but it is a possible solution.

Create a class Response:

class Response {
    body : string;
    constructor() {
        this.body = '';
    }
    write(text : string) {
        this.body = this.body + text;
    }
    end() {}
}

and then make res a object of type Response:

res = new Response();

Comments

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.