解决类字段的“@typescript-eslint/no-invalid-this”问题,而不与“@typescript-eslint/no-this-alias”冲突

Gur*_*ofu 2 typescript eslint typescript-class typescript-eslint

在下面的代码中:

\n
import { Vue, Component } from "vue-property-decorator";  \n\n\n@Component({\n  components: {}\n})\nexport default class ProductViewingAndEditingPage extends Vue {\n\n  private readonly componentsReferencesIDs: {\n    productTitleInputField: string;\n    productPriceInputControl: string;\n  } = {\n    productTitleInputField: "ProductTitle--InputField",\n    productPriceInputControl: "ProductPrice--InputComponent"\n  };\n\n  private readonly productDataFormValidator: InputsGroupValidator = new InputsGroupValidator({\n    controls: {\n      [this.componentsReferencesIDs.productTitleInputField]:\n          this.$refs[this.componentsReferencesIDs.productTitleInputField],\n      [this.componentsReferencesIDs.productPriceInputControl]:\n          this.$refs[this.componentsReferencesIDs.productPriceInputControl]\n    }\n  });\n}\n
Run Code Online (Sandbox Code Playgroud)\n

@typescript/eslint发出@typescript-eslint/no-invalid-this问题(因为它不是 ESLint no-invalid-this,该规则理解类字段。)。

\n

关于概念解决方案的思考

\n

如果我使用componentsReferencesIDs静态类字段,则无法从 vue 模板中检索值。

\n

这里不能使用箭头函数,因为这里是类字段。而且,如果我们使用 alias this,我们将面临no-this-alias规则。

\n

我知道 ESLint 并不是唯一的事实来源。但我想要这样的理由:“因为 \xe3\x80\x88argument\xe3\x80\x89,这个 ESLint 规则不涵盖这种情况。”

\n

Bra*_*her 6

现在,这可以在 ESLint 中正常工作 - 只需更新您的 ESLint 核心和 @typescript-eslint 版本。游乐场示例


以前的过时的繁荣答案:

@typescript-eslint/no-invalid-this只是还没有this添加对类内属性的支持。

扩展规则最近才添加到项目中。当时,作者致力于开发他们需要的功能,即对thisargs 的支持。

作为一个社区维护的项目,我们依靠社区的支持来帮助我们添加规则、添加功能和修复错误。
如果有人想解决这个问题 - 请随时提交 PR - 我相信这实际上应该是一个相对简单的解决方案。

github上的相关问题:https://github.com/typescript-eslint/typescript-eslint/issues/491


顺便说一句,这可能会引发一个问题:“为什么这个问题一年多了还没有得到解决!?”

两个原因:

  1. 当您noImplicitThis打开编译器选项时,如果您使用无效的 .TypeScript 本身会抛出编译器错误。因为this它是由 TS 直接处理的,所以绝大多数用户不觉得需要使用 lint 规则重复错误。
  2. 没有多少用户this在类属性中使用,这意味着用户一开始就不太可能遇到此问题。有些用户不喜欢这种风格的属性,但我相信大多数用户实际上并不知道这样做是有效的。

将这两者放在一起 - 很少有用户使用 lint 规则,并且仍在this类属性中使用的用户更少 - 因此没有足够的人来激励社区修复它。