You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从以字符串传入的标签类型中获取对应属性类型?

解决HTML标签属性类型匹配问题

要实现传入的属性与对应HTML标签严格匹配,只需利用TypeScript内置的JSX.IntrinsicElements类型——它包含了所有标准HTML标签的属性定义。修改createElement函数如下:

import type { ElementType } from 'react';

export const createElement = <C extends keyof JSX.IntrinsicElements>(Component: C) => {
  return (props: JSX.IntrinsicElements[C]) => (
    <Component {...props} />
  );
};

const Some = () => {
  const Textarea = createElement("textarea");
  const Input = createElement("input");

  return (
    <>
      {/* 此处会触发TypeScript错误:textarea标签不支持type属性 */}
      <Textarea placeholder={"123"} type={"color"}/>
      {/* input标签支持type="color",正常通过类型检查 */}
      <Input type={"color"} />
    </>
  )
}

关键说明:

  • 泛型C extends keyof JSX.IntrinsicElements:约束传入的Component必须是合法的HTML标签名(如"textarea"、"input")。
  • props: JSX.IntrinsicElements[C]:直接复用TypeScript内置的对应标签属性类型,确保传入的props完全符合该标签的标准属性定义。
  • 改造后,给Textarea传入type这类非法属性时,TypeScript会自动抛出类型错误,而合法属性则正常通过检查。

内容的提问来源于stack exchange,提问作者Desperado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 18:29:49