VSCode IntelliSense does not autocomplete JavaScript DOM events and methods

后端 未结 2 1403
忘了有多久
忘了有多久 2021-01-05 16:05

I am using Visual Studio Code version 1.17.1.

In *.js file when I type document.querySelector(\"#elementId\").style. I have no IntelliSense

2条回答
  •  渐次进展
    2021-01-05 16:57

    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:

    1. Create file dom.d.ts
    2. Append to it:
    interface NodeSelector {
        querySelector(selectors: K): ElementTagNameMap[K] | null;
        querySelector(selectors: string): E | null;
        querySelectorAll(selectors: K): ElementListTagNameMap[K];
        querySelectorAll(selectors: string): NodeListOf;
    }
    

    Now querySelector returns HTMLElement.

提交回复
热议问题