扩展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
相关产品推荐
相关产品推荐

