Adding the Type of a Custom Element to the DOM API

Ole Ersoy
Dec 18, 2020

--

Scenario

We are developing a custom HelloElement with Typescript.

class HelloElement extends HTMLElement {

greeting = 'Hola!';
}

window.customElements.define('hello-world', HelloElement);

And when we try to use it like this :

const el = document.createElement('hello-world');

el.greeting = 'Hallo'; '

We get this error:

Property ‘greeting’ does not exist on type ‘HTMLElement’.(2339)

Thus we want to remedy this.

The reason it happens is because Typescript is looking for the greeting property at compile time, and it does not yet exist since the statement window.customElements.define is executed at runtime.

Approach

Extend the declaration of HTMLElementTagNameMap

declare global {   
interface HTMLElementTagNameMap {
'hello-world': HelloElement;
}
}

Demo

--

--

Ole Ersoy
Ole Ersoy

Written by Ole Ersoy

Founder of Firefly Semantics Corporation

No responses yet