Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eslint rule no-invalid-this and fat arrow function in class

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?

like image 825
pixel Avatar asked Nov 16 '25 05:11

pixel


1 Answers

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.

like image 116
shn Avatar answered Nov 17 '25 22:11

shn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!