鉴于以下通用类型,是否有任何方法可以从必需的Props
属性继承component
类型,而不必将Props
传递给Override
?
type Override<Props extends {} = {}> = {
component: React.ComponentType<Props>
props?: Props
}
我要实现的目标是
type AnchorProps = { [...] }
const Anchor: React.ComponentType<AnchorProps> = [...]
type ParagraphProps = { [...] }
const Paragraph: React.ComponentType<ParagraphProps> = [...]
type Overrides = {
// i want to do this
[tag in keyof JSX.IntrinsicElements]?: Override
// rather than this
a: Override<AnchorProps>,
p: Override<ParagraphProps>,
[...]
}
const overrides: Overrides = {
a: {
component: Anchor, // type is now `React.ComponentType<AnchorProps>`
props: { [...] }, // type should inherit from `component` and be `AnchorProps`
},
p: {
component: Paragraph, // type is `React.ComponentType<ParagraphProps>`
props: { [...] }, // type should inherit `ParagraphProps`
},
[...]
}
答案 0 :(得分:0)
否,您不能从Props
类型继承component
类型。使用TypeScript不可能做到这一点
如果您正在使用AnchorProps
和ParagraphProps
的自定义界面,而不是标准的React.AnchorHTMLAttributes<HTMLAnchorElement>
和React.HTMLAttributes<HTMLParagraphElement>
但是,如果您的Anchor
组件采用与标准HTMLAnchorElement
相同的道具,则仅需几行就可以实现所需的结果。
declare const Anchor: React.ComponentType<React.AnchorHTMLAttributes<HTMLAnchorElement>>
declare const Paragraph: React.ComponentType<React.HTMLAttributes<HTMLElement>>
type Overrides = {
[tag in keyof JSX.IntrinsicElements]?: {
component: React.ComponentType<JSX.IntrinsicElements[tag]>,
props?: JSX.IntrinsicElements[tag]
}
}
const overrides: Overrides = {
a: {
component: Anchor,
props: {
href: 'str', // ok
broken: true // error, as expected
}
},
p: {
component: Paragraph
}
}
答案 1 :(得分:0)
您需要告诉TypeScript内部元素和自定义道具之间的关系是什么。
interface OverriddenProps extends JSX.IntrinsicElements {
a: AnchorProps;
p: ParagraphProps;
}
创建您的Overrides
映射类型:
type Overrides = {
[Tag in keyof JSX.IntrinsicElements]?: {
component: React.ComponentType<OverriddenProps[Tag]>;
props: OverriddenProps[Tag]
}
}
类型推断现在将正常工作。