VSCode的IntelliSense不能自动完成JavaScript DOM事件和方法。

12

我正在使用Visual Studio Code版本1.17.1。

*.js文件中,当我输入document.querySelector("#elementId").style.时,没有智能感知提示样式(如margin、display等)。 甚至在document.querySelector("#elementId").后面也没有onclick事件提示。

输入图像描述

输入图像描述

我没有使用任何npm包。这只是一个简单的html\css\js项目。

如何开启正确的智能感知提示?谢谢。

2个回答

9
因为querySelector的结果要么是:Element - 最常见的基类,要么是null
如果您已经知道id,则可以使用document.getElementById(),它返回更具体的类的实例 - HTMLElement - 自动完成将按预期工作。
document.getElementById('elementId').

如果您不知道 id,但需要自动完成,您可以使用 JSDoc 类型注释: (参考链接)
/** @type {HTMLElement} */
var el =  document.querySelector(".myclass");

el.

// or without extra variable:
/** @type {HTMLElement} */
(document.querySelector(".myclass")).

我没有真正测试过,但你可以尝试类似这样的方法:

/**
 * @type {function(string): HTMLElement}
 */
var querySelector = document.querySelector.bind(document);

querySelector('.myclass').

另一个选择是更改 TypeScript 类型:

  1. 创建文件 dom.d.ts
  2. 在文件中添加以下内容:
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>;
}

现在querySelector返回HTMLElement。

1
谢谢!我能否设置VS Code在“querySelector”之前隐式添加这个JSDoc?我不想要额外的变量。类似于这样:/** @type {HTMLElement} */(document.querySelector(".className")).style.display = "none"; - Stanislav
有趣的是,/** @type {HTMLElement} */ 只适用于querySelector上的id,而不是class。因此,需要使用一些HTMLElements集合,而不仅仅是{HTMLElement}? - Mark
是的,这个可以工作。实际上,我并不是很喜欢它。强制querySelector返回HTMLElement而不是Element会更好。但不幸的是这是不可能的。但还是谢谢。 - Stanislav
我需要编译这个 TypeScript 吗?只是将 TS 添加到根文件夹并不能帮助我。现在我正在编写原始的 JavaScript。 - Stanislav
不确定,我已经在文件夹中安装和配置了TypeScript。在JS文件顶部添加注释// @ts-check或重新加载编辑器是否有帮助? - Alex
显示剩余5条评论

1
其他答案指向了正确的答案——使用jsdoc进行类型转换——但是我发现,当你在处理联合类型时,只有当你按照typescript要求的方式完全做到了这一点时,它才能始终正常工作:你需要将转换后的表达式括在括号中,并将类型转换文档放在同一行上。来自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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接