React+MUI v5开发遇TypeScript报错Theme无palette属性解决方案问询
MUI v5 + TypeScript 下useTheme访问palette属性类型报错解决方案
问题场景
开发环境为 React v17.0.2 + Material UI v5.0.0,使用TypeScript开发时遇到以下类型问题:
- 从
@emotion/react引入useTheme钩子,调用后访问theme.palette.mode触发TS报错:Property 'palette' does not exist on type 'Theme',但运行时打印theme对象可确认palette属性实际存在,MUI官方的Theme类型定义中也包含该属性 - 尝试从
@mui/material/styles引入Theme类型给theme变量做标注,又收到报错:Type 'Theme' is missing the following properties from type 'Theme': mixins, palette, shadows, transitions, and 6 more. - 尝试给
useTheme传入Theme泛型也报错:Expected 0 type arguments, but got 1,palette不存在的提示依然存在 - 临时通过
theme: any的方式规避了问题,但不符合TypeScript类型规范要求
解决方案
问题根因为引入的useTheme钩子和Theme类型来源不匹配,正确操作是从@mui/material统一引入两者,给theme变量标注Theme类型即可正常使用,代码示例如下:
import { useTheme, Theme } from '@mui/material'; const theme: Theme = useTheme() <Box sx={{backgroundColor: theme.palette.mode}}></Box>
内容的提问来源于stack exchange,提问作者Sean
相关产品推荐
相关产品推荐

