我正在使用custom-elements中的Preact aka Web组件。问题是Typescript抱怨JSX.IntrinsicElements
中没有定义元素-在这种情况下,是check-box
元素:
<div className={styles.option}>
<check-box checked={this.prefersDarkTheme} ref={this.svgOptions.darkTheme}/>
<p>Dark theme</p>
</div>
错误信息(路径省略):
ERROR in MyComponent.tsx
[tsl] ERROR in MyComponent.tsx(50,29)
TS2339: Property 'check-box' does not exist on type 'JSX.IntrinsicElements'.
很不幸,我遇到了以下可能无法解决的问题:
我尝试将以下内容添加到我的typings.d.ts
文件中:
import * as Preact from 'preact';
declare global {
namespace JSX {
interface IntrinsicElements {
'check-box': any; // The 'any' just for testing purposes
}
}
}
我的IDE将导入部分和IntrinsicElements
设为灰色,这表示它没有被使用(?!),而且还是无法正常工作。我仍然收到相同的错误消息。
我什至在file项目中找到了由Google维护的squoosh,他们在其中进行了以下操作以“填充”支持:
在与组件相同的文件夹中,包含以下内容的
missing-types.d.ts
文件,基本上具有与我相同的设置,但是具有index.ts
文件而不是check-bock.ts
,并且它们使用的是TS的较旧版本v3.5.3
:
declare namespace JSX {
interface IntrinsicElements {
'range-input': HTMLAttributes;
}
}
我假设他们的构建没有失败,所以它如何工作以及如何正确定义自定义元素以在preact / react组件中使用它们?
我当前正在使用[email protected]
和[email protected]
。
好,我设法使用module augmentation解决了它:
declare module 'preact/src/jsx' {
namespace JSXInternal {
// We're extending the IntrinsicElements interface which holds a kv-list of
// available html-tags.
interface IntrinsicElements {
'check-box': unknown;
}
}
}
使用HTMLAttributes
接口,我们可以告诉JSX哪些属性可用于我们的自定义元素:
// Your .ts file, e.g. index.ts
declare module 'preact/src/jsx' {
namespace JSXInternal {
import HTMLAttributes = JSXInternal.HTMLAttributes;
interface IntrinsicElements {
'check-box': HTMLAttributes<CheckBoxElement>;
}
}
}
// This interface describes our custom element, holding all its
// available attributes. This should be placed within a .d.ts file.
declare interface CheckBoxElement extends HTMLElement {
checked: boolean;
}