简体   繁体   中英

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM