The 'querySelector' property does not exist on the 'Node' type. in TypeScript

advertisements

I have the following code: 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>

and the ts file test.ts

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

and i got the error.

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

I found the following sentence in MDN

parentNode is the parent of the current node. The parent of an element is an Element node, a Document node, or a DocumentFragment node.

here is my test

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

could someone tell me what's wrong with that?

the version of typescript is 1.4


could someone tell me what's wrong with that

TypeScript's view of the API. At the moment there is no way to say that the type of foo.parentNode depends on the type of foo. Currently it is inferred to always be of type Node and Node does not contain the API querySelector (available on Element)

Fix

Use a type assertion as shown:

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