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


I have the following code: test.html

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

and the ts file test.ts

var box = document.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')
[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)


Use a type assertion as shown:

var box = document.querySelector('#box');