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

问题描述

根据所有这些页面

我希望这能奏效:

/**
 * Destroy current user session.
 */
function logout() {
  const form = document.getElementById('logout-form') as HTMLFormElement;
  form.submit();
}

相反,我在 VS Code 中看到了这个 ESLint 错误

解析错误:意外标记,应为“;”

enter image description here

这种方法也抛出了错误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 非常有帮助。

我认为主要的关键是将我的 parser 文件中的 .eslintrc.js 更改为 parser: '@typescript-eslint/parser',

我也按照指示调整了 pluginsextends

然后我将这些行添加到 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'],