微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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'],

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。