简体   繁体   中英

Problem with JavaScript Intellisense VScode [ts()]

Hello!
I have a ts() JavaScript Intellisense problem in vscode. When I type following lines:

const input = document.querySelector("#input");
const button = document.querySelector("#button");
button.addEventListener("click", () => {
   console.log(input.value);
});

I get an error that states that Property "value" not found in type Element.

Please suggest me!

document.querySelector() will return an Element type by default, which does not have a value property. You need to tell TypeScript a more specific kind of element that you are expecting the query selector to return, as it cannot deduce this from the query string alone.

Given that you expect the query selector to return an HTML input element you would use const input = document.querySelector<HTMLInputElement>("#input"); to narrow down the return type of the query selector. A value property exists on this type so now you can use input.value .

More specifically document.querySelector is a generic function, generics are used when something, such as the return type of a function, can be of more than one type. You can read more about generics and its syntax in the TypeScript documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM