如何用TypeScript组合MUI Typography与react-i18nify Translate组件?
问题
需要在React+MUI的TypeScript环境下创建一个组合组件TypographyTranslate,整合MUI的Typography和react-i18nify的Translate组件,要求能接收两个组件的所有Props,使用方式如下:
<TypographyTranslate variant='caption' value='common.hello' />
尝试用交集类型定义Props,但代码出现错误:
import { Typography, TypographyProps } from '@mui/material' import { Translate, TranslateProps } from 'react-i18nify' interface ITypographyTranslate { props: TypographyProps | TranslateProps } export const TypographyTranslate = ({ props }: ITypographyTranslate) => { return ( <Typography {...props}> <Translate {...props} /> </Typography> ) }
报错信息:
- 使用组件时的错误:
Type '{ variant: string; value: string; }' is not assignable to type 'IntrinsicAttributes & ITypographyTranslate'. Property 'variant' does not exist on type 'IntrinsicAttributes & ITypographyTranslate'.
- 组件内部
Translate的错误:
No overload matches this call. Overload 1 of 2, '(props: TranslateProps): Translate', gave the following error. Type '{ align?: "center" | "left" | "right" | "inherit" | "justify" | undefined; children?: ReactNode; classes?: (Partial<TypographyClasses> & Partial<...>) | undefined; ... 372 more ...; component?: ElementType<...> | undefined; } | { ...; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Translate> & Readonly<TranslateProps>'. ...
请问是否可以通过这种方式实现组件组合?
解决方案
当然可以实现这种组件组合,你的代码核心问题在于Props定义和传递的方式错误:
错误原因分析:
- 你定义的
ITypographyTranslate要求传入一个props属性包裹所有参数,但实际使用时直接把variant、value作为顶层属性传递,TypeScript会报错这些属性不存在。 - 使用
TypographyProps | TranslateProps的联合类型会让TypeScript无法确定当前Props属于哪个组件,传递给Translate时会因为包含Typography的专属Props而出现类型不匹配。
- 你定义的
修正后的代码:
应该使用交集类型合并两个组件的Props,并且直接解构顶层属性,不需要额外的props包裹:
import { Typography, TypographyProps } from '@mui/material'; import { Translate, TranslateProps } from 'react-i18nify'; // 合并两个组件的Props,用交集类型确保同时兼容两者 type TypographyTranslateProps = TypographyProps & TranslateProps; export const TypographyTranslate = (props: TypographyTranslateProps) => { // 拆分Props:提取Translate需要的属性,避免冗余属性传递给Typography const { value, children, ...typographyProps } = props; return ( <Typography {...typographyProps}> <Translate value={value}>{children}</Translate> </Typography> ); };
- 关键优化点:
- 用
TypographyProps & TranslateProps合并Props,组件可直接接收两个组件的所有顶层属性,符合你期望的使用方式。 - 拆分Props,只把
Translate需要的属性(如value、children)传递给它,避免将Typography的专属属性(如variant)传递给Translate,解决类型不匹配问题。 - 若两个组件存在同名Props(如
children),直接传递给Translate即可,因为Typography的子元素会被Translate覆盖。
- 用
内容的提问来源于stack exchange,提问作者Arnau
相关产品推荐
相关产品推荐

