Consider the following:
class MyCustomElement extends HTMLElement {}
customElements.define('my-custom-element', MyCustomElement);
/** @type {MyCustomElement} */
const myCustomElement = document.createElement('my-custom-element');
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The myCustomElement would be an instance of MyCustomElement at runtime (a derivation of HTMLElement); but, type-hinting the myCustomElement makes the JetBrains IDE of PhpStorm to complain:
Initializer type
HTMLElementis not assignable to variable typeMyCustomElement
Surprisingly, the IDE is totally fine on the built-in types:
/** @type {HTMLDivElement} */
const myDiv = document.createElement('div');
So, what should I do to have the very appropriate "typing hints" to the IDE (not using *) while having the warning resolved?!
myCustomElement using the new operator; and it seems to work, but there is no reference on the differences between the approaches (on whether to use new or to use document.createElement(), and why or why-not to choose one over the other?!)
Closure doesn't understand that you're instantiating an instance of MyCustomElement from the document.createElement because it does not understand customElements.define's implications* on its internal type system you're creating an HTMLElement with a tag name of "my-custom-element".
What you'll likely want to do is cast the result of the createElement function (HTMLElement) as MyCustomElement:
/** @type {MyCustomElement} */
const myCustomElement = /** @type {MyCustomElement} */ (document.createElement('my-custom-element'));
*: As far as I know; there is no evidence that they intend to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With