首页 > 解决方案 > 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,如果没有通过

标签: typescripttypescript-generics

解决方案


您可以拥有一个扩展索引类型查询的接口,但您需要将其放入单独的类型别名中(不能直接在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>

推荐阅读