财产'querySelector'在类型'节点'.在TypeScript中
Property 'querySelector' does not exist on type 'Node'. in 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>
和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.json
的lib
列表中的问题。
"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'));
相关文章:
- 节点导出返回一个空对象
- 可以前端maven插件使用节点,npm已经安装
- 在jstree中,如何将指定的节点集中到大型树上
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- 如何从模块链中调用函数.导出到节点中
- Foreach无法在Typescript中工作
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- 扩展SVGTextElement时出现Typescript Uncaught TypeError
- d3基于用户选择动态更新节点
- 为什么无法在TypeScript中导出类实例
- 有条件更新d3.js力图中节点的最佳方法
- Visual Studio 2015 NodeJS/Typescript 覆盖节点启动文件
- 带节点的内存中的Transpile TypeScript
- 如何在 TypeScript / JavaScript 中调用节点.js脚本
- 如何在 Typescript 1.8 中包含非类型化节点模块
- 正在将节点代码库迁移到TypeScript:全局范围
- (TypeScript)正在为Parse SDK(浏览器和节点)创建类型定义
- 现有节点模块的TypeScript定义文件
- 财产'querySelector'在类型'节点'.在TypeScript中
- TypeScript - 类型“节点”上不存在属性“id”