Typescript: document.querySelector should have blur() method

Created on 14 Sep 2016  ·  8Comments  ·  Source: microsoft/TypeScript

TypeScript Version: 1.8.0 / nightly (2.0.0-dev.201xxxxx)
1.8.1
Code

var myBlur = document.querySelector('.blur').blur();

Expected behavior:
No error should be thrown by the compiler.

Actual behavior:
Compiler throws following error:
Property blur does not exist on type Element.

This does not throw for document.getElementById, as document.getElementById is of type HTMLElement. document.querySelector is simply of type Element.

I believe that document.querySelector should be of type HTMLElement.

Bug lib.d.ts good first issue help wanted

Most helpful comment

I think that as type assertion can solve this easily, no change to the definition is necessary.

(document.querySelector(".blur") as HTMLElement).blur();

All 8 comments

Just to note that in both cases, they technically return Element not HTMLElement so it is being pragmatic versus accurate. See: .querySelector and .getElementById.

I was looking at the spec as well but couldn't figure out any way to get a non-HTMLElement out of querySelector. Is it possible?

Allegedly, you can refer to a namespace in CSS and thereby select SVG Elements, though again, pragmatism likely would still outweigh accuracy. That is a lot of work to grab an SVG element.

Fixed in 452227d90219b77aec49b86bff15e7f93e157b09

For this, I changed the general string selector passed to document.querySelector from Element to HTMLElement. This will not only allow you to access classes/id's but web-components in React/NG2.

As @kitsonk states, the practicality of having all HTMLElement methods available is more important then the off chance a developer incorrectly implements the method on a non html element. Though the protection for selecting SVG elements is unnecessary, as the lib already has those generally baked in (see line Line 17649 in lib.d.ts for example).

Should I create a pull request? @RyanCavanaugh @mhegazy?
All tests and lints pass after my committ.

In the spec, querySelecter returns Element https://dev.w3.org/2006/webapi/selectors-api2/#interface-definitions. So I think this pr shouldn't be accepted.

I think that as type assertion can solve this easily, no change to the definition is necessary.

(document.querySelector(".blur") as HTMLElement).blur();

Based on the comment from @falsandtru this issue should be closed, I agree PR on this issue should not be accepted.
Making document as HTMLElement instead of Element will violate W3C spec. Also adding more specificity of HTMLElement is subject to browser DOM and CSS compliance, and imho it's harder to track than to comply with W3C.

I suggest this issue should be closed.

I too agree with @eriawan.

Was this page helpful?
0 / 5 - 0 ratings