TS7041

error TS7041: The containing arrow function captures the global value of ‘this‘.

Broken Code ❌

1
2
3
4
5
6
const myObject = {
name: 'Benny',
myMethod: () => {
return this.name;
},
};

Fixed Code ✔️

Using this is not allowed in arrow functions (source) because arrow functions aren’t made to work with call, apply and/or bind methods (source). We have to replace our arrow function with an anonymous function declaration to prevent that our this context gets captured:

1
2
3
4
5
6
const myObject = {
name: 'Benny',
myMethod: function () {
return this.name;
},
};

Since ECMAScript 2015 (ES6) this can be shortened (Object Literal Property Value Shorthand) to:

1
2
3
4
5
6
const myObject = {
name: 'Benny',
myMethod() {
return this.name;
},
};