admin管理员组文章数量:1426894
The Typescript Lit Element starter project includes this global interface declaration at the bottom of the example element:
declare global {
interface HTMLElementTagNameMap {
'my-element': MyElement;
}
}
Is that necessary? What is it used for?
The Typescript Lit Element starter project includes this global interface declaration at the bottom of the example element:
declare global {
interface HTMLElementTagNameMap {
'my-element': MyElement;
}
}
Is that necessary? What is it used for?
Share Improve this question asked Dec 4, 2020 at 18:15 OleOle 47.6k70 gold badges238 silver badges446 bronze badges1 Answer
Reset to default 9Is that necessary?
No, this declaration is not necessary for your LitElement based custom element to work.
What is it used for?
This is a feature of TypeScript and not specific to LitElement.
This declaration helps TypeScript to provide strong typing when interacting with DOM APIs. The JavaScript DOM API of course does not know or care about types, but TypeScript does. With this mechanism you can add the type of your custom elements to the DOM APIs.
An example might illustrate this better. Assuming this very simple custom element:
class HelloWorldElement extends HTMLElement {
name = 'world'; // public 'name' member with default value
// ... element internals left aside,
// just assume this.name is used somewhere ...
}
window.customElements.define('hello-world', HelloWorldElement);
Now consider using this element with the DOM APIs:
const el = document.createElement('hello-world');
// el has the very generic type HTMLElement
el.name = 'custom elements'; // error! HTMLElement has no member 'name'
TypeScript won't let you. It has no way (yet) of knowing that the tag name hello-world
goes with a HelloWorldElement
instance as the customElements.define(...)
statement is executed at runtime, but type safety is checked at pile time.
But if you extend the declaration of HTMLElementTagNameMap
, TypeScript will know the type of a <hello-world></hello-world>
element:
// with the added declaration
declare global {
interface HTMLElementTagNameMap {
'hello-world': HelloWorldElement;
}
}
const el = document.createElement('hello-world');
// el has type HelloWorldElement
el.name = 'custom elements'; // OK. HelloWorldElement has a string member 'name'
If you want to know more details, you'll find them in the TypeScript Handbook.
本文标签: javascriptLit element typescript project global interface declaration necessaryStack Overflow
版权声明:本文标题:javascript - Lit element typescript project global interface declaration necessary? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745487149a2660432.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论