MUI v5如何为Typography组件的props定义正确的类型?
问题原因
你当前把variant、component属性的类型定义为了过于宽泛的string类型,不符合Material UI Typography内置的枚举类型要求,TS做类型校验时无法通过。
你抛出的TS错误翻译如下:
没有匹配此调用的重载。
第2个重载(共2个)(props: DefaultComponentProps<TypographyTypeMap<{}, "span">>): Element抛出以下错误:
类型string不能分配给类型"button" | "caption" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "inherit" | "overline" | "body1" | "subtitle1" | "subtitle2" | "body2" | undefined。错误码TS2769
解决方案
直接从Typography组件的类型定义中提取对应属性的类型即可,不需要手动枚举所有variant合法值:
第一步:导入对应类型
如果你用的是Material UI v5,导入语句如下:
import { Typography } from '@mui/material' import { PropsWithChildren } from 'react'
第二步:修改TextProps类型定义
直接复用Typography内置的属性类型,不要自定义为string:
interface TextProps { // 直接提取Typography官方定义的variant类型 variant?: Typography['variant'] // 同理提取component官方类型 component?: Typography['component'] // 点击事件类型适配所有HTML元素,不要限定为a标签 onClick?: (event: React.MouseEvent<HTMLElement>) => void } export const Text = ({ children, variant = 'body1', component = 'body1', onClick }: PropsWithChildren<TextProps>) => { return ( <Typography variant={variant} component={component} onClick={onClick}> {children} </Typography> ) }
补充说明
- 这种写法不需要你手动维护variant的合法枚举值,后续MUI官方更新类型定义时,你的代码会自动同步最新的类型,无需额外修改
- 如果需要更完整的类型继承,可以直接继承Typography的所有props:
interface TextProps extends TypographyProps {},不需要单独定义每个属性
内容的提问来源于stack exchange,提问作者Jamie Hutber
相关产品推荐
相关产品推荐

