[英]Lit element typescript project global interface declaration necessary?
The Typescript Lit Element starter project includes this global interface declaration at the bottom of the example element: Typescript Lit Element 入门项目在示例元素的底部包含此全局接口声明:
declare global {
interface HTMLElementTagNameMap {
'my-element': MyElement;
}
}
Is that necessary?那有必要吗? What is it used for?
它是干什么用的?
Is that necessary?
那有必要吗?
No, this declaration is not necessary for your LitElement based custom element to work.不,您的基于 LitElement 的自定义元素不需要此声明即可工作。
What is it used for?
它是干什么用的?
This is a feature of TypeScript and not specific to LitElement.这是 TypeScript 的一项功能,并非特定于 LitElement。
This declaration helps TypeScript to provide strong typing when interacting with DOM APIs.此声明有助于 TypeScript 在与 DOM API 交互时提供强类型。 The JavaScript DOM API of course does not know or care about types, but TypeScript does.
JavaScript DOM API 当然不知道也不关心类型,但 TypeScript 知道。 With this mechanism you can add the type of your custom elements to the DOM APIs.
通过这种机制,您可以将自定义元素的类型添加到 DOM API。
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:现在考虑将此元素与 DOM API 一起使用:
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. TypeScript 不会让你。 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 compile time.由于
customElements.define(...)
语句是在运行时执行的,因此它无法(还)知道标签名称hello-world
与HelloWorldElement
实例一起使用,但在编译时会检查类型安全性。
But if you extend the declaration of HTMLElementTagNameMap
, TypeScript will know the type of a <hello-world></hello-world>
element:但是如果你扩展
HTMLElementTagNameMap
的声明,TypeScript 将知道<hello-world></hello-world>
元素的类型:
// 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 .如果您想了解更多详细信息,您可以在TypeScript 手册中找到它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.