Type web component

Type web component

·

2 min read

This is the problem I come access today. I want to share the solution I found in there.

The problem is like this. Suppose we have a custom web component defined like below.

class C1 extends HTMLElement {
  connectedCallback() {
    const text = this.getAttribute("text");
    this.innerHTML = ">>> " + text + "<<<";
  }
}

customElements.define("c-1", C1);

We can use it in React like below.

function App() {
  return (
    <div>
      <c-1 text="haha"></c-1>
    </div>
  );
}

But because we are using Typescript, we should get an error like below.

So problem is that TypeScript does not recognize this component. We need to define it somehow to let TypeScript know.

So I searched the doc and found the way in here: https://www.typescriptlang.org/docs/handbook/jsx.html#intrinsic-elements.

So we can just follow the doc and define the component to make the error go away.

declare namespace JSX {
  interface IntrinsicElements {
    "c-1": any;
  }
}

And as you can see, we have a prop for this component. So to make it better, we can define our prop params properly like below.

declare namespace JSX {
  interface IntrinsicElements {
    "c-1": {
      text: string;
    };
  }
}

So now not only we can have TypeScript recognize this component, but also make the props typed. If we forget to pass the props, we should get a proper error.