我的应用包含两个文件:(https://codesandbox.io/s/react-ts-muicontainer-override-yywh2)
//index.tsx
import * as React from "react";
import { render } from "react-dom";
import { MuiThemeProvider } from "@material-ui/core/styles";
import { Button, Container, Typography } from "@material-ui/core";
import myTheme from "./myTheme";
function App() {
return (
<MuiThemeProvider theme={myTheme}>
<Container>
<Typography>
<p>Some text</p>
</Typography>
<Button>dummy</Button>
</Container>
</MuiThemeProvider>
);
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
//myTheme.ts
import { createMuiTheme } from "@material-ui/core/styles";
export default createMuiTheme({
overrides: {
MuiButton: {
root: {
backgroundColor: "red"
}
},
MuiTypography: {
root: {
color: "green"
}
},
MuiContainer: {
root: {
backgroundColor: "yellow"
}
}
}
});
该应用程序在黄色背景上显示内容,这意味着我的主题覆盖了工作。但是,myTheme.ts中的整个MuiContainer
键都带有红色下划线,并且错误提示:
类型'{MuiButton:{root:{backgroundColor:string; }; }; MuiTypography:{根:{颜色:字符串; }; }; MuiContainer:{根目录: {backgroundColor:string; }; }; }'无法分配给type “替代”。 对象文字可能仅指定已知属性,并且'MuiContainer'在'Overrides'类型中不存在。ts(2345) createMuiTheme.d.ts(20,3):预期的类型来自属性 在此处以“ ThemeOptions”类型声明的“替代”
实际上,似乎muioverrides.d.ts中的ComponentNameToClassKey接口中缺少MuiContainer
。但是,MuiContainer documentation说:如果使用主题的替代键,则需要使用以下样式表名称:MuiContainer 。所以我认为密钥应该是正确的。
在这种情况下如何解决打字稿类型检查?
答案 0 :(得分:0)
要解决打字稿问题,您可以给 createMuiTheme 作为 any 类型,以快速解决此问题。
import { createMuiTheme } from "@material-ui/core/styles";
export default (createMuiTheme as any)({ // Fixes the typescript warning.
overrides: {
MuiButton: {
root: {
backgroundColor: "red"
}
},
MuiTypography: {
root: {
color: "green"
}
},
MuiContainer: {
root: {
backgroundColor: "yellow"
}
}
}
})
我希望它会有所帮助。谢谢!