为什么MUI的sx prop使用theme getter时会出现TypeScript类型校验失败?
问题解决方法
报错原因
这是MUI 5.0.0-beta版本下,sx属性的类型匹配问题:你传入的theme getter函数参数使用了any类型,不符合SystemStyleObject要求的入参类型签名,所以TS抛出类型错误,运行时不受影响是因为MUI runtime本身确实支持函数格式的sx值。
修复步骤
- 导入所需类型
SystemStyleObject和基础Theme类型都可以从@mui/system包直接导入:
import type { SystemStyleObject, Theme } from '@mui/system';
- 两种可选修复写法
写法1:给theme参数显式标注类型
不用额外声明整个sx对象的类型,TS会自动推导匹配:
<Box sx={(theme: Theme) => ({ border: `1px solid ${theme.palette.primary.main}` })} > 内容 </Box>
写法2:提前声明sx对象的类型
适合样式逻辑较复杂、需要抽离的场景:
const customSx: SystemStyleObject<Theme> = (theme) => ({ border: `1px solid ${theme.palette.primary.main}`, padding: theme.spacing(2) }) <Box sx={customSx}>内容</Box>
可选优化(自定义主题场景)
如果你使用了自定义扩展的MUI主题,可以在全局类型声明文件中添加以下声明,之后使用SystemStyleObject时无需每次传入泛型:
// global.d.ts import type { CustomTheme } from '你的自定义主题文件路径'; declare module '@mui/system' { interface DefaultTheme extends CustomTheme {} }
内容的提问来源于stack exchange,提问作者paws
相关产品推荐
相关产品推荐

