使用@mui的makeStyles时提示Property 'xxx' does not exist on type 'string'报错如何解决
错误原因
你当前给makeStyles传入的样式对象使用了嵌套结构,makeStyles默认的TS类型推断无法识别嵌套的样式结构,会默认把所有顶级key(也就是你的dialog)识别为string类型,自然无法读取dialog下的root等子属性。
解决方案
给makeStyles显式传入泛型声明样式结构即可,有两种常用实现方式:
方式1:手动定义类型接口
import { makeStyles, StyleRules } from '@material-ui/core/styles'; // 声明你的classes整体结构 interface CustomStyleClasses { dialog: { root: string; backdrop: string; paperScrollPaper: string; paper: string; } } // 给makeStyles传入泛型绑定类型 const useStyles = makeStyles((): StyleRules<keyof CustomStyleClasses, CustomStyleClasses> => ({ dialog: { root: { position: 'absolute' }, backdrop: { position: 'absolute' }, paperScrollPaper: { overflow: 'visible' }, paper: { background: 'none', boxShadow: 'none', overflow: 'hidden' } }, }))
方式2:通过typeof自动推导类型
如果不想手动写接口,可以把样式对象抽离后直接用typeof推导类型:
import { makeStyles } from '@material-ui/core/styles'; // 抽离样式对象,加as const锁定类型 const styleConfig = { dialog: { root: { position: 'absolute' }, backdrop: { position: 'absolute' }, paperScrollPaper: { overflow: 'visible' }, paper: { background: 'none', boxShadow: 'none', overflow: 'hidden' } }, } as const; // 泛型传入typeof styleConfig自动绑定结构 const useStyles = makeStyles<typeof styleConfig>(() => styleConfig);
修改后classes会被正确识别为你定义的嵌套结构,所有属性调用的类型错误都会消失。
内容的提问来源于stack exchange,提问作者Roger Peixoto
相关产品推荐
相关产品推荐

