I want to create a component in React with MUI (using Typescript) which is the composition of two other components:
- Typography (from MUI)
- Translate (From https://github.com/sealninja/react-i18nify)
I would like this custom component can receive props from both, e.g.
<TypographyTranslate variant='caption' value='common.hello' />
I defined my custom component prop using typescript intersection
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>
)
}
but I get this error when using the component
Type '{ variant: string; value: string; }' is not assignable to type 'IntrinsicAttributes & ITypographyTranslate'.
Property 'variant' does not exist on type 'IntrinsicAttributes & ITypographyTranslate'.
And the Translate in my custom component complains that all the props from Typography don’t exist
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>'.
...
...
is really possible to do composition this way?
1
I think the issue might:
- Typecasting to
TypographyProps | TranslateProps
but your
component expects to handle bothTypography
andTranslate
props simultaneously. - You’re spreading all the props to both
Typography
andTranslate
, which causes conflicts because both components expect different sets of props.
Try changing to below and try
import { Typography, TypographyProps } from '@mui/material';
import { Translate, TranslateProps } from 'react-i18nify';
type TypographyTranslateProps = TypographyProps & TranslateProps;
export const TypographyTranslate: React.FC<TypographyTranslateProps> = ({ variant, value, ...props }) => {
return (
<Typography variant={variant} {...props}>
<Translate value={value} />
</Typography>
);
};