在Typescript中使用自定义JSX杂注的DOM元素的动态道具



使用自定义JSX杂注时,是否可以允许扩展DOM元素属性?

类似于情绪&样式化的组件使用css道具并在其jsx杂注中管理逻辑。我也想这样做,但使用可以通过泛型类型配置的属性?

例如:

// @jsx jsx
import { jsx } from 'my-lib';
...
<button<{ primary: boolean }> css={styles} primary={primary}>
Hello world
</button>

我当前的类型定义如下:

interface CustomAttributes {
css?: CSSProperties;
}

declare module 'react' {
interface DOMAttributes extends CustomAttributes {}
}
declare global {
namespace JSX {
interface IntrinsicAttributes extends CustomAttributes {}
}
}

我天真的解决方案是这样的:

interface CustomAttributes {
css?: CSSProperties;
}

declare module 'react' {
interface DOMAttributes<DynamicProps> extends CustomAttributes, DynamicProps {}
}
declare global {
namespace JSX {
interface IntrinsicAttributes<DynamicProps> extends CustomAttributes, DynamicProps {}
}
}

相关问题:样式化组件';s';css';带有TypeScript 的道具

您肯定可以添加一组固定的属性,但我不知道如何使其动态。这工作得很好,并将可选的boolean属性"primary"添加到所有JSX元素中。

interface CustomAttributes {
primary?: boolean;
}
declare global {
namespace JSX {
interface IntrinsicAttributes extends React.Attributes, CustomAttributes {}
}
}

当我们试图使其通用时,我们会遇到麻烦,因为原始接口不是通用的。添加通用<T>会导致此错误:

TS2428:"IntrnsicAttributes"的所有声明都必须具有相同的类型参数。

继承链中有一堆接口用于react确定道具(React.DetailedHTMLProps(,因此您可以在其他可能的位置添加道具。

interface DOMAttributes<T>interface HTMLAttributes<T>泛型,但泛型类型T指的是元素的类型(即button(,而不是元素的泛型参数。可以将某些道具添加到所有button元素中。

我无法克服的问题是,当JSX.IntrinsicElements.button不是泛型时,如何使button元素本身具有泛型,就像您的示例一样。我没有足够的信心说这绝对是不可能的,但我做不到。

最新更新