Fix the problem of "@typescript-eslint/no-invalid-this" in class fields without causing issues with "@typescript-eslint/no-this-alias"

Take a look at the code snippet below:

import { Vue, Component } from "vue-property-decorator";  


@Component({
  components: {}
})
export default class ProductViewingAndEditingPage extends Vue {

  private readonly componentsReferencesIDs: {
    productTitleInputField: string;
    productPriceInputControl: string;
  } = {
    productTitleInputField: "ProductTitle--InputField",
    productPriceInputControl: "ProductPrice--InputComponent"
  };

  private readonly productDataFormValidator: InputsGroupValidator = new InputsGroupValidator({
    controls: {
      [this.componentsReferencesIDs.productTitleInputField]:
          this.$refs[this.componentsReferencesIDs.productTitleInputField],
      [this.componentsReferencesIDs.productPriceInputControl]:
          this.$refs[this.componentsReferencesIDs.productPriceInputControl]
    }
  });
}

@typescript/eslint raises an issue with @typescript-eslint/no-invalid-this (as it does not comply with ESLint's no-invalid-this, but rather understands class fields).

Reflections on Possible Solutions

If I were to make componentsReferencesIDs a static class field, it would no longer be possible to retrieve values from the vue template.

Due to the nature of being a class field, arrow functions cannot be utilized here. Additionally, aliasing this would lead to complications with the no-this-alias rule.

I acknowledge that ESLint is not the ultimate authority. However, I seek justification such as "due to 〈argument〉, this ESLint rule may not cover this specific scenario."

Answer №1

ESLint is now functioning correctly after updating the ESLint core and @typescript-eslint versions. You can check out this playground example


An outdated answer for posterity:

The rule

@typescript-eslint/no-invalid-this
did not support this in class properties before, but it has been added to the project recently.

This feature was implemented based on community contributions. If anyone wants to address this issue, please submit a PR as it should be a simple fix.

Refer to the issue on GitHub: https://github.com/typescript-eslint/typescript-eslint/issues/491


Why hasn't this been resolved for over a year?

There are two main reasons:

  1. When using the noImplicitThis compiler option in TypeScript, an error will be thrown if an invalid this is used. Many users rely on this TypeScript feature and don't see the need for duplicating the error with a lint rule.
  2. Not many users utilize this in class properties, so the issue may not be encountered by most users. Some users may not even be aware that it's valid to use this in such a way.

Combining these factors - low usage of the lint rule and limited use of this in class properties - there hasn't been enough community motivation to address the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for defining types for specific CSS properties in TypeScript, such as variables

Perhaps there are already solutions out there, and I appreciate it if you can share a link to an existing thread. Nevertheless... In React, when I use the style prop, I receive good autocompletion and validation features like this example: https://i.sstat ...

Priority is given to strings over numbers

Here's some code I'm working with: <tbody> <tr> <td class="float-left"> <!-- {{selectedTemplat?.modifiedAt | da ...

What is the process of expanding a npm module with TypeScript?

I am currently using joi in conjunction with @types/joi for TypeScript. Joi's extend method allows for the extension of joi by creating a new instance without altering the original joi library. I have successfully created an extended instance using th ...

Error message "After the upgrade to Angular 15, the property 'selectedIndex' is not recognized in the type 'AppComponent'."

My Ionic 6 app with capacitor has been updated in the package.json file. These are the changes: "dependencies": { "@angular/common": "^15.1.0", "@angular/core": "^15.1.0", "@angular/forms": "^15.1.0", "@angular/platform-browser": "^15.1. ...

Is there a way to automatically close the previous accordion when scrolling to a new one on the page?

Currently, I am working with the material-ui accordion component and facing an issue where all accordions are initially opened. As I scroll down the page and reach a new accordion, I want the previous ones to automatically close. The problem arises when tr ...

Is there a way to assign a value to an Angular-specific variable using PHP?

In the development of my Angular 4 application, I encountered an issue while receiving JSON data based on an id value through a PHP script. Upon examining the code, it seems that there should be a value passed into this.PropertiesList. examineProperties(i ...

Customizing the spacing for jsx-curly in Eslint

I am currently grappling with the challenge of creating a specific rule for curly spacing within jsx elements in React, but I am struggling to find the right configuration. My goal is to achieve the following scenario: <Component attr1={this.props.val ...

Delete element from the array upon removal from the AutoComplete component

I am facing a challenge with the Material UI AutoComplete component in my project. The issue arises when I try to update the state of the associateList after clearing a TextField. Additionally, I would appreciate any guidance on how to handle removing an ...

Empty array being returned by Mongoose after calling the populate() function

I've been struggling for the past 3-4 hours, banging my head against the wall and scouring countless articles here on StackOverflow, but I just can't seem to get my response to populate an array correctly. I'm working with Express.js, Typesc ...

Is there a way to deactivate the spin buttons for an input number field?

Is there a way to create an input element with type number in Vue using createElement() in TypeScript and then disable the spin buttons for increment and decrement? I attempted to use the following CSS: input[type=number]::-webkit-inner-spin-button, input ...

Ways to conceal an element in Angular based on the truth of one of two conditions

Is there a way to hide an element in Angular if a specific condition is true? I attempted using *ngIf="productID == category.Lane || productID == category.Val", but it did not work as expected. <label>ProductID</label> <ng-select ...

Encountering an error with the Next Auth adapter in TypeScript when attempting to modify the default User interface

This is my first time using TypeScript and I am attempting to customize the default User interface for next-auth. I have experimented with the following code: next-auth.d.ts import { User } from "next-auth" import { JWT } from "next-auth/j ...

Mismatch between TypeScript library and Angular web application: certain properties are absent

I am currently facing a dilemma with my two angular projects. The first one is a library while the second one is a regular Angular webapp. Within my library project, I have the following code snippet: class User { firstName: string; lastName: stri ...

In TypeScript, the first element of an array can be inferred based on the second element

Let's consider a scenario where we have a variable arr, which can be of type [number, 'number'] or [null, 'null']. Can we determine the type of arr[0] based on the value of arr[1]? The challenge here is that traditional function ov ...

Configuring routes for Angular4 router is a vital step in creating a

Issue: I am currently setting up routes for my application, aiming to structure the URL as https://localhost:4200/hero=id, where the 'id' will be dynamically selected. However, this setup is not functioning as expected. If I attempt to use a URL ...

Greetings, Angular2 application with TypeScript that showcases the beauty of the world

I've been working on my first angular2 program and noticed some deviations from the expected output. typings.json: { "ambientDependencies": { "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f ...

Is there a way to specify to a JavaScript variable that it must have a defined value upon creation?

getPersonneById(id: number): Personne{ const personne = this.personnes.find( personne => { return personne.id == id; }); return personne; } An error message is displayed: Unable to assign type 'Person | undefined' to type &a ...

How can I eliminate the white bar elements from my dropdown menu? Also, seeking guidance on replacing an empty <div> tag in a boolean query

Can anyone help me understand the strange white border around my dropdown menu and guide me on how to remove it? I am currently using DropdownButton from react bootstrap. I have attempted to adjust the CSS with no success. Here is the code I tried: .Navig ...

Encountering the error "No overload matches this call" while utilizing useQuery in TypeScript may indicate a mismatch in function parameters

My issue lies with TypeScript and types. Here is the API I am working with: export const clientAPI ={ //... getOptions: async (myParam: number) => get<{ options: Options[]; courses: any[] }>(`/courses?myParam=${myParam}`)().then((result) =& ...

Facing numerous "error TS1005" messages when performing a gulp build due to node_modules/@types/ [prop types] and [react] index.d.ts with SPFx Webpart

I am currently in the process of developing a custom spfx webpart that includes a feature to display link previews. In order to achieve this functionality, I integrated this specific library. However, I encountered some challenges during the implementation ...