在 React 和 TypeScript 中使用 Web Components
2022-07-27 · 201 chars · 2 min read
最近在接入 giscus 的时候遇到个 Web Component 的 ts 的类型问题,反复试了几次才解决,写篇笔记记录下。
giscus 提供了一个比较轻量的 web 版本,使用方法大概是这样的:
<giscus-widget id="comments" repo="giscus/giscus" repoid="MDEwOlJlcG9zaXRvcnkzNTE5NTgwNTM=" category="General" categoryid="MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyNzk2NTc1" mapping="specific" term="Welcome to giscus!" reactionsenabled="1" emitmetadata="0" inputposition="top" theme="light" lang="en" loading="lazy" ></giscus-widget>
我想的是直接丢在 JSX 里,但是 IDE 提示了错误:
Property 'giscus-widget' does not exist on type 'JSX.IntrinsicElements'.ts(2339)
ts 不认识新加的 web component 标签,那就参考默认的 html 标签写一下,例如 IntrinsicElements.span 的定义是:
React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>
照猫画虎写一下 giscus-widget 的:
interface GiscusWidgetAttributes<T> extends React.HTMLAttributes<T> {
[repo: string]: string
[repoid: string]: string
// ...
}
declare namespace JSX {
interface IntrinsicElements {
'giscus-widget': React.DetailedHTMLProps<GiscusWidgetAttributes<HTMLElement>, HTMLElement>
}
}


