TypeScript Version: 2.2.1
Code
document.activeElement.isContentEditable // type error
(document.activeElement as HTMLElement).isContentEditable
document.querySelector('[contenteditable="true"]').addEventListener("mousedown", (e) => {
e.target.getBoundingClientRect() // type error
(e.target as Node).getBoundingClientRect()
(e.target as Element).getBoundingClientRect()
(e.target as HTMLElement).getBoundingClientRect()
})
Expected behavior:
I would expect there to be no type-errors here because they all work in the browser...
Actual behavior:
I get random unexpected type-errors and keep having to cast types.
I apologize if I don't know what I'm talking about and this is actually a question, but it seems like a bug to me. If not, I'd love to see some clarification in the docs about the subtleties of these types.
Basically EventTarget is the most general type, of which Element is a subtype, and HTMLElement is a subtype of that. If you get back a thing from the DOM, we generally have no idea which it is, and you should add a type assertion to "add in" the specific external knowledge that you have about the structure of your particular DOM layout.
It's possible, for example, that the .target of an event is not an Element (you can add event listeners to XMLHttpRequest, for example, and XMLHttpRequest does not have a getBoundingClientRect method).
hmm, well in the event listener above, it seems like the target should always be HTMLElement based on the type that I'm adding the event listener to. Is it possible that we just need some stricter type annotations? Or is this just the way it is?
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
Most helpful comment
Basically EventTarget is the most general type, of which Element is a subtype, and HTMLElement is a subtype of that. If you get back a thing from the DOM, we generally have no idea which it is, and you should add a type assertion to "add in" the specific external knowledge that you have about the structure of your particular DOM layout.
It's possible, for example, that the
.targetof an event is not an Element (you can add event listeners to XMLHttpRequest, for example, and XMLHttpRequest does not have a getBoundingClientRect method).