如何在 TypeScript 中的 document.getElementById() 方法的类型转换期间处理 ESLint 错误? [英] How to handle ESLint error during type casting of document.getElementById() method in TypeScript?
问题描述
根据所有这些页面:
这种方法也抛出了错误:
const form = <HTMLFormElement>document.getElementById('logout-form');
我已经在 .tsx 文件和 .ts 文件中尝试了相同的功能.
我做错了什么?
附言我正在使用 Prettier 和 ESLint 和 https://github.com/airbnb/javascript 规则和 https://stackoverflow.com/a/64166241/470749
解决方案https://khalilstemmler.com/blogs/typescript/eslint-for-typescript/#Installation-and-setup 非常有帮助.
我认为主要的关键是将
.eslintrc.js
文件中的parser
更改为parser: '@typescript-eslint/parser',代码>.
我也按照指示调整了
plugins
和extends
.然后我将这些行添加到我的
.eslintrc.js
中的rules
对象中,因为 https://stackoverflow.com/a/64024916/://我们必须禁用基本规则(因为它可以报告不正确的错误)并替换它(https://stackoverflow.com/a/64024916/):'no-use-before-define': 'off','@typescript-eslint/no-use-before-define': ['error'],
According to all of these pages:
- https://stackoverflow.com/a/52491932/470749
- https://stackoverflow.com/a/65514898/470749
- https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions
I expected this to work:
/** * Destroy current user session. */ function logOut() { const form = document.getElementById('logout-form') as HTMLFormElement; form.submit(); }
Instead, I see this ESLint error in VS Code:
Parsing error: Unexpected token, expected ";"
This approach threw errors, too:
const form = <HTMLFormElement>document.getElementById('logout-form');
I've tried this same function in both a .tsx file and a .ts file.
What am I doing wrong?
P.S. I'm using Prettier and ESLint and https://github.com/airbnb/javascript rules and https://stackoverflow.com/a/64166241/470749
解决方案https://khalilstemmler.com/blogs/typescript/eslint-for-typescript/#Installation-and-setup was super helpful.
I think the main key was to change
parser
in my.eslintrc.js
file toparser: '@typescript-eslint/parser',
.I also adjusted
plugins
andextends
as instructed.Then I added these lines to the
rules
object in my.eslintrc.js
because of https://stackoverflow.com/a/64024916/:// We must disable the base rule (since it can report incorrect errors) and replace it (https://stackoverflow.com/a/64024916/): 'no-use-before-define': 'off', '@typescript-eslint/no-use-before-define': ['error'],
这篇关于如何在 TypeScript 中的 document.getElementById() 方法的类型转换期间处理 ESLint 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!