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

如何为Material UI Icon的fontSize属性定义TypeScript类型?

解决方案

要为iconFontSize属性添加正确的类型定义,你可以复用MUI中SvgIcon组件的fontSize属性类型,具体实现如下:

  • 从@mui/material/SvgIcon导入SvgIconProps类型
  • 将iconFontSize的类型指定为SvgIconProps['fontSize'],确保它和MUI原生SvgIcon组件的fontSize参数类型完全一致

完整代码示例:

import { SvgIconComponent } from '@mui/icons-material'
import { Typography, TypographyProps} from '@mui/material'
// 导入SvgIconProps类型
import { SvgIconProps } from '@mui/material/SvgIcon';

type Props = TypographyProps & {
  Icon: SvgIconComponent
  iconFontSize: SvgIconProps['fontSize']
}

export const IconTypography = ({
  Icon,
  iconFontSize = 'inherit',
  columnGap = 1,
  children,
  ...props
}: Props) => {
  return (
    <Typography display="flex" alignItems="center" columnGap={columnGap} {...props}>
      <Icon fontSize={iconFontSize} />
      {children}
    </Typography>
  )
}

这种方式的优势在于,iconFontSize会自动继承MUI的SvgIcon组件支持的所有有效值(比如'inherit'、'small'、'medium'、'large'或具体数值),同时获得完整的类型检查和IDE自动提示。

内容的提问来源于stack exchange,提问作者xandert.93

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:15:20