Simple question. Why this one works:
const heroText = {
height: 400,
display: "flex",
justifyContent: "center",
}
<Grid item sx={heroText}>Some text</Grid>
And this one will give you the Typescript error ("No overload matches this call."):
const heroText = {
height: 400,
display: "flex",
justifyContent: "center",
flexDirection: "column",
}
<Grid item sx={heroText}>Some text</Grid>
If you do not believe me that just adding the flexDirection: "column"
will produce Typescript error, you can try it for yourself.
I am working with new MUI 5, React and Typescript.
CodePudding user response:
The inferred type for flexDirection
on your heroText
object is string
but the sx
prop is expecting something more specific (a string union of "column" | "column-reverse" | "row" | "row-reverse", etc...)
The preferred solution here is probably to add a type for heroText
:
const heroText: SxProps = {
height: 400,
display: "flex",
justifyContent: "center",
flexDirection: "column",
}
<Grid item sx={heroText}>Some text</Grid>
Another solution could be to assert a more specific type for flexDirection
with as const
const heroText = {
height: 400,
display: "flex",
justifyContent: "center",
flexDirection: "column" as const,
}
<Grid item sx={heroText}>Some text</Grid>
CodePudding user response:
You can use const assertion
to cast the value to an object literal. This will prevent the value of each property from being widen (e.g. The type of display is "flex"
instead of string
which is not a valid value of the display
):
const heroText = {
height: 400,
display: "flex",
justifyContent: "center",
} as const
Another solution is to declare the SxProp
type, this is a bit longer but has the advantage of giving you intellisense when setting the value:
import { SxProps } from '@mui/system';
const sx: SxProps = {
height: 400,
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
};