javascript - JS 文件中的 TS 警告:“类型 X 上不存在属性 X”:是否可以编写更干净的 JavaScript?
问题描述
我目前正在发现 TypeScript。我使用以下代码:
const someClass = document.querySelector(".that-class");
const someId = document.getElementById("elemId").value;
和我之前的许多其他人一样,当然还有更多人会遇到以下错误:
Property 'style' does not exist on type 'Element'.
Property 'value' does not exist on type 'HTMLElement'.
<HTMLElement>
我通过添加或在需要时修复了我的 .ts 文件中的这些错误<HTMLInputElement>
,工作正常。但是当我编译我的 .ts 时,我会从 .js 文件中的 VSCode 收到一些 TS 警告。
我的问题很简单:有没有办法避免在 JS 文件中出现这些错误(即:是否有一种“更简洁”的方式来编写 JavaScript 代码)?还是我应该简单地忽略这些 TS 警告?
非常感谢您的帮助!
解决方案
这里有一些好消息:我找到了我正在寻找的答案。
给你一些额外的背景信息:我正在处理一个表单,需要使用 JavaScript/TypeScript 操作一些用户输入。这是代码:
<form id="my-form" action="index.html" method="get" onsubmit="return showValue();">
<input type="text" name="username">
<input type="text" name="full-name">
<input type="password" name="password">
<button type="button" onclick="showValue();">Send</button>
</form>
还有我的 JavaScript 代码:
function showValue() {
const myForm = document.getElementById("my-form").value;
console.log(myForm);
return 1;
}
这将返回警告:"Property 'value' does not exist on type 'HTMLElement'
.
这可以通过在 TypeScript 中添加此代码的一些变体来轻松解决:
const myForm = (<HTMLInputElement>document.getElementById("my-form")).value;
太好了,TypeScript 中不再有警告。但编译后生成的 JavaScript 文件会再次显示警告:"Property 'X' does not exist on type X"
因此,我的问题是,如何编写代码才能完全不收到任何警告?
我希望找到以下答案:
function showValue() {
const myForm = document.forms.my-form;
console.log(myForm?.username.value);
return 1;
}
我花了很长时间才找到它并在规范文档中进行了一些挖掘,但希望这似乎可行!
我仍然要感谢大家的评论,他们对我找到答案的方式帮助很大。
推荐阅读
- javascript - 如何从数组创建对象?
- python - 帖子下的评论
- postgresql - 在具有 300 个整数和 300 个字符(20)的表上插入失败
- c# - WPF:如何将窗口的 ShowInTaskbar 属性绑定到代码隐藏值?
- indexing - Power Query: erase row above on certain conditions "_"
- html - 如何指示 HTML 文档是草稿还是存根?
- visual-studio - 检查工作的 C 编译器:“cl.exe - 已跳过”:Visual Studio 2019
- python - 如何按日期时间顺序对作为字符串格式的日期的列名进行排序
- regex - Ruby正则表达式从仅包含一个数字的字符串中提取一个数字并修剪逗号后的部分
- javascript - 使用 alt 属性搜索 img 表并显示整行