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?
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).
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();