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

The Typescript Lit Element starter project includes this global interface declaration at the bottom of

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745487149a4629816.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信