【问题标题】:TS(7015) in a document.form : "Element implicitly has an 'any' type because index expression is not of type "number"document.form 中的 TS(7015):“元素隐式具有‘任何’类型,因为索引表达式不是“数字”类型
【发布时间】:2022-01-22 01:23:59
【问题描述】:

我正在尝试获取用户在表单中输入的值。

这就是我的表单的样子:

<form name="myForm">
   <span class="myFormSpan">+</span>
   <input type="text" placeholder="My answer" name="myFormUserInput">
   <button type="button" class="formButton">Ok</button>
</form>

我想得到用户在输入表单中输入的内容,所以我的打字稿代码如下所示:

formInputs.addEventListener("click", () => {
   const userInput: any = document.forms["myForm"].elements["myFormUserInput"].value;
   console.log(userInput);
});

效果很好,只是我不断收到 TypeScript 警告ts(7015) : Element implicitly has an 'any' type because index expression is not of type 'number'.。我尝试将我的代码更改为document.forms[0],这不会删除警告,并尝试在这里和那里添加一些类型规范,但没有更成功......

我想保持隐式警告(与那里写的解决方案相反:Element implicitly has an 'any' type),因为我想了解这个问题并有办法解决它

有什么想法吗?

非常感谢!

【问题讨论】:

  • document.forms[0] 也给你同样的错误?
  • 嗨@TusharShahi!是的,不幸的是......我先尝试过,但没有改变任何东西 - 这就是为什么我不知道警告来自哪里:-D

标签: javascript typescript


【解决方案1】:

在表单和元素上使用基于数字的索引应该会清除警告。

formInputs.addEventListener("click", () => {
    const userInput: any = (document.forms[0].elements[0] as HTMLInputElement).value;
    console.log(userInput);
});

但你真的应该考虑使用 document.querySelector()

无论在 DOM 中的位置或顺序如何,这都会找到正确的表单/输入

像这样:

formInputs.addEventListener("click", () => {
    const userInput = document.querySelector<HTMLInputElement>('form[name="myForm"] input[name="myFormUserInput"]') || null

    if (userInput !== null)
        console.log(userInput.value);
});

【讨论】:

    猜你喜欢
    • 2021-08-01
    • 2023-02-15
    • 2022-06-12
    • 2023-04-01
    • 2018-04-25
    • 2021-10-11
    • 2017-03-14
    • 2016-07-23
    • 1970-01-01
    相关资源
    最近更新 更多