I understand what I need to do, get the type definition for Typography.variant However I am not sure how to get these really.
interface TextProps {
variant?: string
component?: string
onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void
}
export const Text = ({ children, variant = 'body1', component = 'body1', onClick }: PropsWithChildren<TextProps>) => {
return (
<Typography variant={variant} component={component} onClick={onClick}>
{children}
</Typography>
)
}
No overload matches this call.
Overload 2 of 2, '(props: DefaultComponentProps<TypographyTypeMap<{}, "span">>): Element', gave the following error.
Type 'string' is not assignable to type '"button" | "caption" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "inherit" | "overline" | "body1" | "subtitle1" | "subtitle2" | "body2" | undefined'. TS2769
I believe this is how you can fix the type errors, both variant and component are not string, you can look at the Typography type definition file here for reference.
import Typography, { TypographyTypeMap } from "@mui/material/Typography";
interface TextProps {
variant?: TypographyTypeMap["props"]["variant"];
component?: React.ElementType;
onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void;
}
I've had the same problem, and I could fix by this way. Basing in on your code:
import React from 'react';
import { Variant } from '@mui/material/styles/createTypography';
interface TextProps {
variant?: Variant
component?: React.ElementType
onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void
}
export const Text = ({ children, variant = 'body1', component = 'body1', onClick }: PropsWithChildren<TextProps>) => {
return (
<Typography variant={variant} component={component} onClick={onClick}>
{children}
</Typography>
)
}
There is another casting to the concerning element using 'as'. Eg:
<Typography variant={variant as Variant } component={component as React.ElementType } onClick={onClick}>
{children}
</Typography>
This way is most used when are used flat objects, but in your case that you've used an interface the best practice is to define their properties types into the interface.
Thumbs up!