React JS转TS项目使用makeStyles抛出类型错误如何解决?
解决方案
问题根源说明
你遇到的两个报错分别对应两个独立问题:
- TS2345类型错误:是TypeScript对字符串字面量的类型收窄逻辑导致,
"relative"默认被推断为string类型,无法匹配Material UI要求的PositionProperty字面量联合类型 - 解析错误:是Babel配置错误+文件后缀不正确,导致无法识别TypeScript的
as类型断言语法
具体修改步骤
1. 修正Babel配置
你当前的@babel/preset-typescript被错误放置在@babel/preset-env的参数数组中,且缺少React预设,修改为以下配置:
module.exports = api => { api.cache.forever(); return { "presets": [ [ "@babel/preset-env", { "targets": { "node": "8.10" } }], '@babel/preset-typescript', '@babel/preset-react' ], plugins: [ "add-react-displayname", "@babel/plugin-proposal-class-properties", "@babel/plugin-proposal-object-rest-spread" ] }; }
2. 修改样式文件后缀
将AdminStyle.js重命名为AdminStyle.tsx,告知Babel和TypeScript该文件需要解析TS语法。
3. 修正样式定义
使用Material UI提供的createStyles工具包裹样式对象,自动完成类型收窄,无需手动添加as断言:
import { createStyles, Theme } from '@material-ui/core/styles'; import { drawerWidth, transition, container } from "../../material-dashboard-react"; const appStyle = (theme: Theme) => createStyles({ wrapper: { position: "relative", top: "0", height: "100vh" }, // 剩余其他样式保持不变即可 mainPanel: { [theme.breakpoints.up("md")]: { width: `calc(100% - ${drawerWidth}px)` }, overflow: "auto", position: "relative", float: "right", ...transition, maxHeight: "100%", width: "100%", overflowScrolling: "touch" }, content: { marginTop: "70px", padding: "30px 15px", minHeight: "calc(100vh - 123px)" }, container, map: { marginTop: "70px" } }); export default appStyle;
4. 修正Admin.tsx中makeStyles调用
无需手动传入theme参数,makeStyles会自动注入theme:
const useStyles = makeStyles((theme: Theme) => appStyle(theme)); export default function Admin({ ...rest }) { const classes = useStyles(); // 剩余代码保持不变 return ( <div className={classes.wrapper}> {handleSideBarLogin() ? null : <Sidebar routes={routes} logoText={"02DesignStudio"} logo={logo} image={image} handleDrawerToggle={handleDrawerToggle} open={mobileOpen} color={color} {...rest} /> } </div> ); }
内容的提问来源于stack exchange,提问作者AS10
相关产品推荐
相关产品推荐

