-
document.querySelector("input#name")
returnsElement
, even though it should clearly beHTMLInputElement
. Using #TypeScript 4.1 inferred Template Literal Types, I made a parser to more accurately type the result, check it out! #WebDev #JavaScript gist.github.com/dgp1130/ac36e63744cdeffcbc7522387662f722 -
This parses the provided selector, extracts the tag name, and then looks up that tag name to get the associated element. It's able to handle all CSS combinators and operators (let me know if I missed one). I'm not totally convinced this is a *good* idea, but it is a cool one!
-
This does hit the recursion limit for overly-complex queries, but it's good enough for 99% of use cases IMHO. I also discovered that pseudo-elements don't work in
querySelector()
. This parser also catches that mistake and turns the runtime error into a compile-time error! -
I'm really interested to see what the community thinks of this of this use case. @buildsghost made a similar JSON parser (github.com/jamiebuilds/json-parser-in-typescript-very-bad-idea-please-dont-use), this is just a (slightly) less-bad use case of the same idea.