typescript - React + Typescript:基于 Prop 的动态类
问题描述
我有一个组件,我在其中传递了一个名为的道具HtmlTag
,并且基于它的值,我想使用基于 html 标记的正确道具来扩展道具接口。
我尝试创建一个充当地图的类型,然后尝试扩展它,例如
type AllAttrs = {
a: AnchorHTMLAttributes,
button: ButtonHTMLAttributes
}
并暂时尝试以下
interface Props extends AllAttrs["a"] {
sanitize?: string;
}
我得到“一个接口只能扩展其他接口”
这就是我使用组件的方式:
<Element
Component="a"
... more props
>Test</Element>
目标是让 TS 抱怨缺少 props,比如 href,如果没有通过
解决方案
您可以拥有一个扩展索引类型查询的接口,但您需要将其放入单独的类型别名中(不能直接在extends
子句中)。
然而,这不是正确的方法。在道具中使用交集类型将允许推理按预期工作(请参见此处):
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>
推荐阅读
- android - 数据绑定返回 null
- php - 自定义请求的中间件
- mysql - 对于每个号码,查找仅使用该号码发布的广告
- python - 如何让 Python3.7 指向另一个 Python 解释器
- xml - 无法将值“System.Object[]”转换为类型“System.Xml.XmlDocument”。错误:“'&' 是一个意外的标记。预期的标记是 ';'
- javascript - 如何从 FileReader.readAsText 恢复原始 blob?
- python - 如何在海龟中制作出与填充颜色不同的线条颜色
- commercetools - 如何从 json 文件创建新的 CustomTypes 和 CustomField?
- fortran - Fortran 多态变量和 OpenMP
- python - 绘制簇矩阵