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

TypeScript中通过Props动态生成标题元素的类型错误排查

解决TypeScript动态HTML标题标签的TS2322类型错误

问题原因

你代码里的size被定义为宽泛的string类型,TypeScript无法确定HeadingTag是合法的HTML标题元素,因此默认将其归类为IntrinsicAttributes类型——这个类型不包含children、className这类HTML元素常用属性,直接触发了类型不匹配的错误。

解决步骤

  • 把size的类型从string改为具体的标题标签联合类型:'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6',限制它只能取合法的标题标签值。
  • (可选)给HeadingTag显式指定React.ElementType类型,让TypeScript明确这是一个可渲染的元素类型,增强类型提示的准确性。

修改后的完整代码

import React from "react";
import styles from "./Header.module.css";

interface Props {
  children: React.ReactNode;
  containerStyle?: React.CSSProperties;
  id: string;
  // 限制size为合法的标题标签取值
  size?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
  title?: string;
  titleStyle?: React.CSSProperties;
}

export default function Header({
  children,
  containerStyle,
  id,
  size = "h3",
  title,
  titleStyle,
}: Props) {
  // 显式指定类型,让TS明确这是一个可渲染的元素
  const HeadingTag: React.ElementType = size;
  return (
    <div className={styles.headerContainer} style={containerStyle}>
      <HeadingTag className={styles.header} style={titleStyle} id={id}>
        {title}
      </HeadingTag>
      <div className={styles.close}>{children}</div>
    </div>
  );
}

原理说明

通过限制size的取值范围,TypeScript能够正确推断HeadingTag对应的HTML元素类型,从而识别className、style、id以及子元素等属性的合法性,彻底解决类型不匹配的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 13:54:22