类型“Element”上不存在属性“checked”,而变量是 NodeList

问题描述 投票:0回答:1

尝试使用以下代码选择所有无线电输入及其检查状态

  const radioInput = document.querySelectorAll("input[type=radio]");
  radioInput.forEach((r) => (r.checked = r.defaultValue === 'whatever'));

这在 javascript 中工作,但现在尝试转换为typsscript,现在它

forEach()

内出现以下打字错误

类型“Element”上不存在属性“checked”。

当我们将鼠标悬停在 radioInput 变量上时,其显示

NodeList<Element>

tsconfig.json 有以下条目

"lib": [
      "es2022",
      "dom",
      "dom.iterable"
    ],

我们该如何解决这个问题?

已经检查过类似的问题,大多数答案都与React相关,而我的代码仅用打字稿编写(.ts,而不是.tsx)

工作演示

dom typescript-typings
1个回答
0
投票

要访问选中的元素,您需要将元素视为

HTMLInputElement
而不是
HTMLElement
,即
(r: HTMLInputElement)

这是您的演示中的示例:

// Import stylesheets
import './style.css';

// Write TypeScript code!

const radioInput = document.querySelectorAll('input[type=radio]');
radioInput.forEach((r: HTMLInputElement) => (r.checked = r.defaultValue === 'X'));

const enum Shape {
  Circle,
  Square,
}

console.log(Shape['1']);
© www.soinside.com 2019 - 2024. All rights reserved.