javascript - 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
);但是,类型提示会使myCustomElement
PhpStorm 的 JetBrains IDE 抱怨:
初始化器类型
HTMLElement
不可分配给变量类型MyCustomElement
令人惊讶的是,IDE 在内置类型上完全没问题:
/** @type {HTMLDivElement} */
const myDiv = document.createElement('div');
那么,在解决警告的同时
,我应该怎么做才能向 IDE(不使用)提供非常合适的“打字提示” ?!*
我可以实例化
myCustomElement
usingnew
运算符;并且它似乎有效,但是没有关于方法之间差异的参考(关于是否使用new
或使用document.createElement()
,以及为什么或为什么不选择一个而不是另一个?!)
解决方案
Closure 不理解您正在从 实例化 MyCustomElement 的实例,document.createElement
因为它不理解customElements.define
' 对其内部类型系统的影响*,您正在创建一个标签名为“my-custom-element”的 HTMLElement。
您可能想要做的是将createElement
函数 ( HTMLElement
) 的结果转换为MyCustomElement
:
/** @type {MyCustomElement} */
const myCustomElement = /** @type {MyCustomElement} */ (document.createElement('my-custom-element'));
*: 我所知道的; 没有证据表明他们打算这样做。
推荐阅读
- sql-server - 数据总是从以前的数据库中获取,而不是从新的数据库中获取
- c# - Unity如何仅使用坐标允许对象在某个边界内移动
- python - Python多进程无法腌制opencv videocapture对象
- spring-boot - 为什么 SBA JMX Bean 管理报告错误?
- python - 在不同的行上打印每个参数
- javascript - CSS过渡下拉菜单,应该很简单
- python - 删除一系列标题中的字符串
- android - 隐藏 Android Navigator 显示边框
- querydsl - QueryDSL 上缺少 FROM
- java - Hortonworks HDFS 名称节点在启动时出现 tryLock 问题