英文:
How to type Material UI Icon's fontSize prop?
问题
import { SvgIconComponent } from '@mui/icons-material'
import { Typography, TypographyProps } from '@mui/material'
type Props = TypographyProps & {
Icon: SvgIconComponent
iconFontSize: /* 插入类型这里! */
}
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>
)
}
英文:
I've composed the component below, and I need to apply a type for the custom iconFontSize
prop. How can I do this?
import { SvgIconComponent } from '@mui/icons-material'
import { Typography, TypographyProps} from '@mui/material'
type Props = TypographyProps & {
Icon: SvgIconComponent
iconFontSize: /* insert type here! */
}
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>
)
}
Thanks in advance!
答案1
得分: 1
你可以将 `iconFontSize` 定义为联合类型的 'inherit' | 'large' | 'medium' | 'small':
```typescript
type Props = TypographyProps & {
Icon: SvgIconComponent
iconFontSize: "inherit" | "small" | "medium" | "large"
}
如果你想使用 MUI 类型定义文件中的确切类型,你也可以这样做:
import { OverridableStringUnion } from '@mui/types';
fontSize?: OverridableStringUnion<
'inherit' | 'large' | 'medium' | 'small',
SvgIconPropsSizeOverrides
>;
OverridableStringUnion
类型本质上是这样定义的:
export type OverridableStringUnion<T extends string | number, U = {}> = GenerateStringUnion<
Overwrite<Record<T, true>, U>
>;
在 MUI 文档中查看类型定义:https://mui.com/material-ui/api/svg-icon/
<details>
<summary>英文:</summary>
You can type `iconFontSize` as a union type of 'inherit' | 'large' | 'medium' | 'small':
```typescript
type Props = TypographyProps & {
Icon: SvgIconComponent
iconFontSize: "inherit" | "small" | "medium" | "large"
}
If you want to use the exact type from the MUI type definition file, you can alternatively use:
import { OverridableStringUnion } from '@mui/types';
fontSize?: OverridableStringUnion<
'inherit' | 'large' | 'medium' | 'small',
SvgIconPropsSizeOverrides
>;
The OverridableStringUnion
type is in turn defined as such:
export type OverridableStringUnion<T extends string | number, U = {}> = GenerateStringUnion<
Overwrite<Record<T, true>, U>
>;
See the type definition in the MUI docs here: https://mui.com/material-ui/api/svg-icon/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论