在MUI与TypeScript中自定义Typography属性遇报错求助
MUI自定义Typography属性时组件提示不存在的解决方法
自定义调色板功能正常,但给Typography添加tab属性后,主题配置阶段无报错,可组件中访问theme.typography.tab时会提示“tab不存在”。
问题原因
只扩展了TypographyOptions接口(用于主题配置的类型校验),但没有扩展Typography接口——theme.typography实际对应的类型是Typography,未扩展的话自然识别不到新增的tab属性。
解决步骤
- 同时扩展两个类型接口
import "@mui/material/styles/createTypography"; import { Typography } from "@mui/material/styles/createTypography"; declare module "@mui/material/styles/createTypography" { // 扩展主题配置时的选项类型 interface TypographyOptions { tab?: React.CSSProperties; } // 扩展theme.typography的实际类型 interface Typography { tab?: React.CSSProperties; } }
- 主题配置保持不变
const theme = createTheme({ typography: { h3: { fontWeight: typographyFonts.H3, // color: themePalette.ARCBLUE, }, tab: { fontFamily: "Raleway", }, }, });
- 组件中正常使用
const StyledTab = styled(Tab)(({ theme }) => ({ ...theme.typography.tab, // 此处不再报错 textTransform: "none", fontWeight: "700", fontSize: "1rem", minWidth: 10, marginLeft: "25px", }));
内容的提问来源于stack exchange,提问作者Carlos Escobar
相关产品推荐
相关产品推荐

