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

TypeScript报错:显式声明的size属性不存在于组件类型中

解决TypeScript提示Button组件size属性不存在的问题

问题出在你对DetailedHTMLProps泛型参数的使用方式上:你把自定义的size属性附加到了DOM元素类型(HTMLButtonElement)上,但实际上应该把自定义属性合并到组件Props类型中,而非元素本身的类型。

修正步骤:

  1. 扩展ButtonHTMLAttributes<HTMLButtonElement>类型,将自定义的size、color属性加入其中
  2. 用这个扩展后的类型作为组件的Props类型

修正后的完整代码:

enum ButtonSize {
  large = "large",
  medium = "medium",
  small = "small",
}

// 假设你已定义ColorScheme类型,示例如下:
type ColorScheme = "primary" | "secondary" | "default";

// 定义组件Props:原生button属性 + 自定义属性
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
  size?: ButtonSize;
  color?: ColorScheme;
};

function Button({
  className,
  children,
  color,
  size,
  ...props
}: ButtonProps) {
  // 这里可以编写组件逻辑,比如根据size、color生成类名
  const btnClass = `button ${size || ButtonSize.medium} ${color || "default"} ${className || ""}`;
  
  return (
    <button className={btnClass} {...props}>
      {children}
    </button>
  );
}

为什么原来的写法错误?

DetailedHTMLProps<T, E>中,第二个参数E是DOM元素的类型(比如HTMLButtonElement),它描述的是真实DOM节点的属性,而不是你自定义组件的Props。你需要合并的是第一个参数T(即ButtonHTMLAttributes<HTMLButtonElement>,它包含了所有原生button的Props)和你的自定义属性,这样TypeScript才能识别size、color是组件合法的Props。

如果你不想单独定义ButtonProps类型,也可以直接在函数参数中使用交叉类型:

function Button({
  className,
  children,
  color,
  size,
  ...props
}: ButtonHTMLAttributes<HTMLButtonElement> & {
  size?: ButtonSize;
  color?: ColorScheme;
}) {
  // 组件逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:01:00