首页 > 解决方案 > JetBrains IDE 上的 Javascript:类型提示自治自定义元素实例

问题描述

考虑以下:

class MyCustomElement extends HTMLElement {}
customElements.define('my-custom-element', MyCustomElement);
/** @type {MyCustomElement} */
const myCustomElement = document.createElement('my-custom-element');
//                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

myCustomElement是运行时的实例MyCustomElement(的派生HTMLElement);但是,类型提示会使myCustomElementPhpStorm 的 JetBrains IDE 抱怨:

初始化器类型HTMLElement不可分配给变量类型MyCustomElement

令人惊讶的是,IDE 在内置类型上完全没问题:

/** @type {HTMLDivElement} */
const myDiv = document.createElement('div');

那么,在解决警告的同时 ,我应该怎么做才能向 IDE(不使用提供非常合适的“打字提示” ?!*


我可以实例化myCustomElementusingnew运算符;并且它似乎有效,但是没有关于方法之间差异的参考(关于是否使用new或使用document.createElement(),以及为什么或为什么不选择一个而不是另一个?!)

标签: javascriptidephpstormjsdoctype-hinting

解决方案


Closure 不理解您正在从 实例化 MyCustomElement 的实例,document.createElement因为它不理解customElements.define' 对其内部类型系统的影响*,您正在创建一个标签名为“my-custom-element”的 HTMLElement。

您可能想要做的是将createElement函数 ( HTMLElement) 的结果转换为MyCustomElement

/** @type {MyCustomElement} */
const myCustomElement = /** @type {MyCustomElement} */ (document.createElement('my-custom-element'));

*: 我所知道的; 没有证据表明他们打算这样做。


推荐阅读