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

扩展HTMLProps接口触发TS2430错误:接口扩展不正确

问题分析与解决方案

错误根源

你猜错了,不是className重复定义的问题——接口扩展时重复声明同类型的属性(比如这里className都是string | undefined)是TypeScript允许的。真正的错误是你新增的wrap属性和HTMLProps<HTMLTableCellElement>中原生的wrap属性类型冲突:

  • 原生wrap是HTML <th>元素的标准属性,类型为string | undefined(用于指定文本换行规则)
  • 你自定义的wrap是boolean | undefined,类型不兼容导致TS2430错误

解决方案

方案1:重命名自定义属性(推荐)

直接把自定义的wrap改成其他名字,避免和原生属性冲突:

import cx from 'classnames';
import { HTMLProps } from 'react';

import styles from './index.module.scss';

export interface IProps extends HTMLProps<HTMLTableCellElement> {
  title?: string;
  className?: string;
  isWrap?: boolean;
}

export const Th = ({ title, className, isWrap, ...rest }: IProps) => {
  return (
    <th
      data-title={title}
      {...rest}
      className={cx(isWrap && styles.wrap, className)}
    />
  );
};

方案2:移除原生wrap属性后扩展

如果你一定要用wrap作为自定义属性名,可以用Omit工具类型剔除原生的wrap属性,再添加自己的:

import cx from 'classnames';
import { HTMLProps } from 'react';

import styles from './index.module.scss';

export interface IProps extends Omit<HTMLProps<HTMLTableCellElement>, 'wrap'> {
  title?: string;
  className?: string;
  wrap?: boolean;
}

export const Th = ({ title, className, wrap, ...rest }: IProps) => {
  return (
    <th
      data-title={title}
      {...rest}
      className={cx(wrap && styles.wrap, className)}
    />
  );
};

补充说明

  • 原生HTML属性的类型定义可在TypeScript的lib.dom.d.ts中查看,能提前避免自定义属性名和原生属性冲突
  • 扩展HTMLProps时,只要新增属性名不与原生属性重名、类型不冲突,就能正常继承所有原生属性类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:02:53