Reaction+TypeScrip:基于道具的动态类 [英] React + Typescript: dynamic class based on a Prop
本文介绍了Reaction+TypeScrip:基于道具的动态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个组件,我正在传递一个名为HtmlTag
的道具,并且根据它的值,我想用基于html标记的正确道具来扩展道具接口。
我尝试创建一个充当映射的类型,然后尝试扩展它,例如
type AllAttrs = {
a: AnchorHTMLAttributes,
button: ButtonHTMLAttributes
}
目前正在尝试以下操作
interface Props extends AllAttrs["a"] {
sanitize?: string;
}
我得到"一个接口只能扩展其他接口"
我是这样使用组件的:
<Element
Component="a"
... more props
>Test</Element>
目标是让TS抱怨如果道具没有通过就会丢失道具,比如HREF
推荐答案
您可以有一个扩展索引类型查询的接口,但您需要将其放入单独的类型别名中(它不能直接位于extends
子句中)。
然而,这不是正确的方法。在道具中使用交集类型将允许推理按预期工作(请参见here):
type AllAttrs = {
a: AnchorHTMLAttributes<HTMLAnchorElement>,
button: ButtonHTMLAttributes<HTMLButtonElement>
}
function Element<T extends keyof AllAttrs>({ Component, ...rest}: { Component: T} & AllAttrs[T]){
return <Component {...rest as any} ></Component>
}
let r = <Element
Component="a"
href=""
>Test</Element>
//Error href not on button
let r2 = <Element
Component="button"
href=""
>Test</Element>
这篇关于Reaction+TypeScrip:基于道具的动态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文