最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Lit element typescript project global interface declaration necessary? - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 9

Is 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.

发布评论

评论列表(0)

  1. 暂无评论