如何为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
相关产品推荐
相关产品推荐

