简体   繁体   English

如何在 TypeScript 中的 document.getElementById() 方法类型转换期间处理 ESLint 错误?

[英]How to handle ESLint error during type casting of document.getElementById() method in TypeScript?

According to all of these pages:根据所有这些页面:

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:相反,我在 VS Code 中看到了这个 ESLint 错误:

Parsing error: Unexpected token, expected ";"解析错误:意外的令牌,应为“;”

在此处输入图像描述

This approach threw errors, too: const form = <HTMLFormElement>document.getElementById('logout-form');这种方法也引发了错误: const form = <HTMLFormElement>document.getElementById('logout-form');

I've tried this same function in both a.tsx file and a.ts file.我在 a.tsx 文件和 a.ts 文件中都尝试过同样的 function 。

What am I doing wrong?我究竟做错了什么?

PS I'm using Prettier and ESLint and https://github.com/airbnb/javascript rules and https://stackoverflow.com/a/64166241/470749 PS 我正在使用 Prettier 和 ESLint 以及https://github.com/airbnb/javascript规则和https://stackoverflow.com/a/64166241/470749

https://khalilstemmler.com/blogs/typescript/eslint-for-typescript/#Installation-and-setup was super helpful. https://khalilstemmler.com/blogs/typescript/eslint-for-typescript/#Installation-and-setup非常有帮助。

I think the main key was to change parser in my .eslintrc.js file to parser: '@typescript-eslint/parser', .我认为主要的关键是将我的.eslintrc.js文件中的解析器更改为parser parser: '@typescript-eslint/parser', .

I also adjusted plugins and extends as instructed.我还按照说明调整了pluginsextends

Then I added these lines to the rules object in my .eslintrc.js because of https://stackoverflow.com/a/64024916/ :然后我将这些行添加到我的 .eslintrc.js 中的rules .eslintrc.js因为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'],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM