属性'query'上不存在属性'querySelector'.在TypeScript中

再见田*_*田园犬 7 javascript typescript

我有以下代码: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>
Run Code Online (Sandbox Code Playgroud)

和ts文件test.ts

var box = document.querySelector('#box');
console.log(box.parentNode.querySelector('#box'));
Run Code Online (Sandbox Code Playgroud)

我得到了错误.

Error:(2, 28) TS2339: Property 'querySelector' does not exist on type 'Node'.
Run Code Online (Sandbox Code Playgroud)

我在MDN中找到了以下句子

parentNode是当前节点的父节点.元素的父级是Element节点,Document节点或DocumentFragment节点.

这是我的考试

var ul = document.querySelector('ul')
undefined
ul.parentNode.toString()
[object HTMLDivElement]"
Run Code Online (Sandbox Code Playgroud)

谁能告诉我这有什么问题?

打字稿的版本是1.4

bas*_*rat 18

有人可以告诉我这有什么问题

TypeScript的API视图.目前没有办法说这种类型foo.parentNode取决于类型foo.目前推断它始终是类型Node,Node不包含API querySelector(可用Element)

固定

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

var box = document.querySelector('#box');
console.log((<Element>box.parentNode).querySelector('#box'));
Run Code Online (Sandbox Code Playgroud)


con*_*exo 8

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

const box = document.querySelector('#box');
console.log((box.parentNode as HTMLElement).querySelector('#box'));
Run Code Online (Sandbox Code Playgroud)


Avo*_*ion 6

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

const formRef = useRef(null as HTMLElement | null);

const form = formRef?.current?.querySelector('form');
Run Code Online (Sandbox Code Playgroud)