Javascript In astro
I used my javascript in script tag inside astro. But it's showing me red underlines but the code works fine and shows no error in the javascript. What's the reason.
On hover it says Property value doesn't exist on type "Element".
It's happening for
.click .key .value .style
Something it doesn't show underline and appears out of no where.
2 Replies
This is likely because either your editor, Astro, or both, are checking and enforcing type definitions (this checks that stuff will work before you try to run it).
document.querySelector returns a type of Element, however the properties you're accessing are only available on HTMLElements
If you know that your query will return an actual HTMLElement, you can tell whatever is checking types that you know what you're doing by writing the following;
Note that HTMLElement does not mean <html>, it means any XML element which belongs to the HTML specification, for example <a>, <p>, <div>, etc.
There's also SVGElement for svg stuff such as <path> and <g>
Element captures all of these. If you're familiar with what inheritance is in OOP, this is the same thing; HTMLElement inherits Element, HTMLAnchorElement and HTMLDivElement both inherit HTMLElement, etc.
an extra tip;
If you know what kind of element you're going to get, but don't know what the specific name for it is in terms of it's type, you can just type in HTML either in the angle brackets (typescript only) or in the curly braces after @type and press ctrl + space in VSCode, it will give you a list of suggestions you can scroll through, or keep typing to narrow down the search.Got it. Thank for the extra tip. 💛