I have following class:
export class MyClass {
private foos: Foo[];
constructor(foos: Foo[]) {
this.foos = foos;
}
getByA = (myA: Mya): Foo => {
return this.foos.find(foo => foo.a === myA) ?? unknownFoo();
};
}
unfortunately, in my fat arrow function, I get a warning about invalid this:
ESLint: Unexpected 'this'.(no-invalid-this)
My eslint plugin version is 4.15.1
Is there anything that I can do to make this rule work correctly apart from disabling it?
You are getting this error because when you create an arrow function, you are creating an object that could be called in a different context of your class. So when getByA is executed, it could be in a context where this does not exist or is different.
One option is to bind the context to the arrow function:
getByA = (myA: Mya): Foo => {
return this.find(foo => foo.a === myA) ?? unknownFoo();
}.bind(this.foos);
For more resources on this error and examples on how to correctly use this in the correct context, look here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With