You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用TypeScript添加或禁用MUI主题Typography的字重配置选项

MUI主题自定义字重配置方案

要实现主题新增自定义字重、同时禁用指定内置字重的需求,可以通过TypeScript模块扩展完成,具体操作如下:

  • 新增类型声明文件
    在项目src目录下新建mui.d.ts(需确保该文件路径被tsconfig.json的include配置包含),添加以下类型扩展代码:
import '@mui/material/styles';

declare module '@mui/material/styles' {
  interface Typography {
    fontWeightSemiBold: number;
  }
  interface TypographyOptions {
    fontWeightSemiBold?: number;
    // 禁用指定字重,传入时会触发TS报错
    fontWeightLight?: never;
    fontWeightMedium?: never;
  }
}
  • 配置主题
    按照预期方式定义主题即可,新增字重会获得完整类型提示,被禁用的字重无法传入:
export const theme = createTheme({
  typography: {
    fontWeightSemiBold: 600,
  },
});
  • 组件调用
    直接在Typography的sx属性中引用自定义字重不会触发TypeScript报错:
<Typography sx={{ fontWeight: 'fontWeightSemiBold' }}>Hello</Typography>

内容的提问来源于stack exchange,提问作者Ioannis Potouridis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 14:06:04