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

如何在TypeScript中扩展section元素的类型?

解决TypeScript中React组件继承section元素Props的问题

在React + TypeScript中,扩展section元素的Props类型其实和扩展div的方式几乎一致,你遇到的HTMLSectionElement不存在的问题,大概率是TypeScript配置中未包含DOM类型定义,或是拼写失误。以下是具体实现方案:

方案1:直接使用HTMLSectionElement(推荐)

HTMLSectionElement是标准DOM API的内置类型,TypeScript默认包含该类型(前提是你的tsconfig.json中lib数组包含"dom")。直接按如下方式定义即可:

import { HTMLAttributes } from "react";

export interface IContainerProps extends HTMLAttributes<HTMLSectionElement> {
  // 在这里添加组件专属的自定义Props
  customProp?: string;
}

// 组件使用示例
const Container = ({ customProp, ...restProps }: IContainerProps) => {
  return (
    <section {...restProps}>
      {customProp && <span>{customProp}</span>}
    </section>
  );
};

方案2:使用元素字面量类型替代

如果遇到类型查找异常,也可以直接传入元素标签名字面量"section"到HTMLAttributes的泛型参数中,效果完全一致:

import { HTMLAttributes } from "react";

export interface IContainerProps extends HTMLAttributes<"section"> {
  customProp?: string;
}

检查TypeScript配置

如果仍然提示HTMLSectionElement不存在,请确认你的tsconfig.json中compilerOptions.lib包含"dom":

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"]
    // 其他配置项...
  }
}

内容的提问来源于stack exchange,提问作者Ala Eddine Menai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:10:59