TypeScript编译报错:'children'属性不存在于'IntrinsicAttributes & CardProps'类型
TypeScript 4.5.4中扩展导入接口时children属性类型错误问题
错误信息
Type error: Type '{ children: Element[]; className: string; border: true; disabled: boolean; }' is not assignable to type 'IntrinsicAttributes & CardProps'. Property 'children' does not exist on type 'IntrinsicAttributes & CardProps'. > 79 | <Card/
代码结构
types.ts
export interface BaseComponentProps { children?: ReactNode | undefined; className?: string; style?: Record<string, unknown>; onClick?: React.MouseEventHandler<HTMLElement>; onMouseOver?: React.MouseEventHandler<HTMLElement>; onMouseLeave?: React.MouseEventHandler<HTMLElement>; key?: number | string | null; 'data-testid'?: string; }
card.tsx
import type { BaseComponentProps } from 'src/types'; interface CardProps extends BaseComponentProps { border?: boolean; disabled?: boolean; } export function Card({ border = false, disabled = false, className, children }: CardProps): JSX.Element { ... }
问题与解决方案
该问题确实和跨文件导入接口并扩展有关,在TypeScript 4.5.x的特定场景下,外部导入接口中的可选children属性无法被正确合并到扩展后的接口中,导致JSX传参时类型校验失败。
原因
当BaseComponentProps在外部文件定义并导入时,TypeScript类型检查器对跨文件接口继承的可选属性推导存在边界问题,未能将children属性正确纳入CardProps的类型集合中;而将接口移到同文件或重复定义children时,类型检查器能直接识别属性,错误自然消失。
解决方法
显式继承
children类型
在CardProps中显式声明children,复用原接口的类型定义,无需重复写类型:interface CardProps extends BaseComponentProps { border?: boolean; disabled?: boolean; children?: BaseComponentProps['children']; }使用React内置函数组件类型
借助React.FC(或React.VFC),它默认包含children属性,可省去手动处理:import type { BaseComponentProps } from 'src/types'; import type { FC } from 'react'; interface CardProps extends BaseComponentProps { border?: boolean; disabled?: boolean; } export const Card: FC<CardProps> = ({ border = false, disabled = false, className, children }) => { // 组件逻辑 };升级TypeScript版本
此问题在TypeScript 4.6及以上版本已被修复,升级到更高版本可彻底解决这类跨文件接口继承的类型识别问题。
内容的提问来源于stack exchange,提问作者Craig
相关产品推荐
相关产品推荐

