VSCode IntelliSense does not autocomplete JavaScript DOM events and methods

别说谁变了你拦得住时间么 提交于 2020-01-30 05:19:38

问题


I am using Visual Studio Code version 1.17.1.

In *.js file when I type document.querySelector("#elementId").style. I have no IntelliSense hints for styles (like margin, display, etc.). Even no onclick event hint after document.querySelector("#elementId").

I don't use any npm packages. It is just simple html\css\js project.

How to turn on correct IntelliSense hints? Thanks.


回答1:


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<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.




回答2:


The other answer points to the correct answer – type casting with jsdoc – but I've found that this only works consistently when you do it exactly as typescript wants when dealing with union types: you need to wrap the casted expression in parentheses and place the type cast doc on the same line. The snippet from a permalink to the wiki:

// We can "cast" types to other types using a JSDoc type assertion
// by adding an `@type` tag around any parenthesized expression.

/**
 * @type {number | string}
 */
var numberOrString = Math.random() < 0.5 ? "hello" : 100;
var typeAssertedNumber = /** @type {number} */ (numberOrString)


来源:https://stackoverflow.com/questions/46797322/vscode-intellisense-does-not-autocomplete-javascript-dom-events-and-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!