Because result of the querySelector
is either:
Element - the most general base class or null
If you already know id you can use document.getElementById() - which returns instance of more specific class - HTMLElement - autocomplete will work as expected.
document.getElementById('elementId').
If you don't know id, but want autocomplete you can use JSDoc type annotations:
/** @type {HTMLElement} */
var el = document.querySelector(".myclass");
el.
// or without extra variable:
/** @type {HTMLElement} */
(document.querySelector(".myclass")).
I haven't really tested it but you can try something like that:
/**
* @type {function(string): HTMLElement}
*/
var querySelector = document.querySelector.bind(document);
querySelector('.myclass').
Another choice would be alter typescript types:
- Create file
dom.d.ts
- Append to it:
interface NodeSelector {
querySelector<K extends keyof ElementTagNameMap>(selectors: K): ElementTagNameMap[K] | null;
querySelector<E extends HTMLElement = HTMLElement>(selectors: string): E | null;
querySelectorAll<K extends keyof ElementListTagNameMap>(selectors: K): ElementListTagNameMap[K];
querySelectorAll<E extends HTMLElement = HTMLElement>(selectors: string): NodeListOf<E>;
}
Now querySelector returns HTMLElement.