财产'querySelector'在类型'节点'.在TypeScript中

Property 'querySelector' does not exist on type 'Node'. in TypeScript

本文关键字:TypeScript 节点 querySelector 财产 类型      更新时间:2023-09-26

我有以下代码:test.html

<!DOCTYPE html>
<html>
<head lang="zh-CN">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title></title>
</head>
<body>
    <div id="container">
        <div id="box"></div>
    </div>
    <script src="test.js"></script>
</body>
</html>

和ts文件测试.ts

var box = document.querySelector('#box');
console.log(box.parentNode.querySelector('#box'));

我犯了错误。

Error:(2, 28) TS2339: Property 'querySelector' does not exist on type 'Node'.

我在MDN 中发现了以下句子

parentNode是当前节点的父节点。元素的父级是element节点、Document节点或DocumentFragment节点

这是我的测试

var ul = document.querySelector('ul')
undefined
ul.parentNode.toString()
[object HTMLDivElement]"

有人能告诉我这是怎么回事吗?

typescript的版本是1.4

有人能告诉我怎么了吗

API的TypeScript视图。目前没有办法说foo.parentNode的类型取决于foo的类型。目前,它被推断为总是Node类型,并且Node不包含API querySelector(在Element上可用(

修复

使用如图所示的类型断言:

var box = document.querySelector('#box');
console.log((<Element>box.parentNode).querySelector('#box'));

对于那些寻找使用Typescript和JSX(.tsx(的解决方案的人:

const box = document.querySelector('#box');
console.log((box.parentNode as HTMLElement).querySelector('#box'));

对于任何在React Hooks/tsx中遇到这个问题的人,我用as HTMLElement | null更新了我的useRef声明,然后我可以使用可选的链接而不会出错。

const formRef = useRef(null as HTMLElement | null);
const form = formRef?.current?.querySelector('form');

使用

let box = <Element>document.querySelector('#box');

parentNode成员返回父节点,父节点可以是Element或node类型。您必须使用parentElement来遍历DOM树,而不是使用parentNode来遍历XML树。

var box = document.querySelector('#box');
console.log(box.parentElement.querySelector('#box'));

我使用的是create-react-app 2.1的TS设置。

对我来说,这是一个将dom添加到tsconfig.jsonlib列表中的问题。

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

如果在.js文件中使用@ts-check,那么有一个干净的解决方案——只需检查节点是否是Element的实例或它应该是什么:

const box = document.querySelector('#box');
const parentNode = box?.parentNode;
if (!(parentNode instanceof Element)) {
  throw new Error('box.parentNode is not an Element');
}
console.log(parentNode.querySelector('#box'));