首页 > 解决方案 > 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 警告?

非常感谢您的帮助!

标签: javascripttypescriptvisual-studio-code

解决方案


这里有一些好消息:我找到了我正在寻找的答案。

给你一些额外的背景信息:我正在处理一个表单,需要使用 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;
}

我花了很长时间才找到它并在规范文档中进行了一些挖掘,但希望这似乎可行!

我仍然要感谢大家的评论,他们对我找到答案的方式帮助很大。


推荐阅读