本文介绍了TypeScript模块增强不起作用:类型';PaletteColorOptions';上不存在属性';Main';的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在处理Material-UI,并尝试在整个调色板中使用颜色系统。编译时似乎有一些问题,尽管它在运行时工作得很好。是否有人可以帮助我解决以下错误:
错误:
这里也有Stackblitz:https://stackblitz.com/edit/react-up6bjl-hx1bbh?file=demo.tsx
编码:
import * as React from 'react';
import {
createTheme,
Theme,
ThemeProvider,
PaletteOptions
} from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
declare module '@material-ui/core/styles' {
interface SimplePaletteColorOptions {
lighter?: string;
darker?: string;
}
interface PaletteColor {
lighter?: string;
darker?: string;
}
}
const Default = () : PaletteOptions => {
return {
primary: {
lighter: '#ddd',
light: '#ddd',
main: '#ddd',
dark: '#ddd',
darker: '#ddd'
},
};
};
export default function CustomColor() {
const defaultColors = Default();
const palette: PaletteOptions = {
...defaultColors,
divider: defaultColors.primary?.main, // error in compile. Cannot find 'main'
};
const theme: Theme = createTheme({
palette
});
console.log(theme.palette.primary.light);
return (
<ThemeProvider theme={theme}>
<Button color="primary" variant="contained">
neutral
</Button>
</ThemeProvider>
);
}
推荐答案
打字错误与模块扩充无关。问题只是defaultColors
的类型是PaletteOptions
。PaletteOptions
defines primary to be of type PaletteColorOptions。
以下是PaletteColorOptions的定义及其生成类型:
export type PaletteColorOptions = SimplePaletteColorOptions | ColorPartial;
export interface SimplePaletteColorOptions {
light?: string;
main: string;
dark?: string;
contrastText?: string;
}
export type ColorPartial = Partial<Color>;
export interface Color {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
A100: string;
A200: string;
A400: string;
A700: string;
}
所以类型脚本编译器知道defaultColors.primary
是SimplePaletteColorOptions
或ColorPartial
,但是它不知道是哪一个。然后您将引用defaultColors.primary.main
,但除非defaultColors.primary
的类型为SimplePaletteColorOptions
,否则不能保证它会存在。
您可以通过对Default
函数使用更具体的返回类型来修复此问题,该返回类型让tyescript知道primary
的类型是SimplePaletteColorOptions
:
interface DefaultPaletteOptions extends PaletteOptions {
primary?: SimplePaletteColorOptions;
}
const Default = (): DefaultPaletteOptions => {
return {
primary: {
lighter: "#ddd",
light: "#ddd",
main: "#ddd",
dark: "#ddd",
darker: "#ddd"
}
};
};
相关答案:
- How to add custom colors name on Material UI with TypeScript?
- MUI Override Slider color options with module augmentation
这篇关于TypeScript模块增强不起作用:类型';PaletteColorOptions';上不存在属性';Main';的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!