考虑以下:

class MyCustomElement extends HTMLElement {}
customElements.define('my-custom-element', MyCustomElement);
/** @type {MyCustomElement} */
const myCustomElement = document.createElement('my-custom-element');
//                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
myCustomElement在运行时将是MyCustomElement的实例( HTMLElement 的派生);但是,type-hintingmyCustomElement使PhpStorm的JetBrains IDE抱怨:

初始化程序类型HTMLElement不能分配给变量类型MyCustomElement
令人惊讶的是,IDE在内置类型上完全可以:
/** @type {HTMLDivElement} */
const myDiv = document.createElement('div');

因此,在解决警告后,我应该怎么做才能在IDE中获得非常合适的“键入提示”(不使用*)?

我可以使用 myCustomElement 运算符实例化new;似乎可行,但是没有提及这两种方法之间的差异(是否使用new或使用 document.createElement() ,以及为什么或为什么不选择一种?)。

最佳答案

Closure不了解您是从document.createElement实例化MyCustomElement的实例,因为它不了解customElements.define在其内部类型系统上的含义*,因此您正在创建标记名称为“my-custom-element”的HTMLElement 。
您可能要做的是将createElement函数(HTMLElement)的结果转换为MyCustomElement:

/** @type {MyCustomElement} */
const myCustomElement = /** @type {MyCustomElement} */ (document.createElement('my-custom-element'));
*: 我所知道的;没有证据表明他们打算这样做。

关于javascript - JetBrains IDE上的Javascript:自动提示自定义元素实例的类型提示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60596739/

10-11 08:25