如何使用Typescript扩展Material-UI主题?

Typescript总是抱怨调色板中缺少某些属性。如果添加//@ts-

ignore,我的应用程序运行正常,但显然我想避免这种情况。我是Typescript的新手,这是我尝试过的。

import createMuiTheme, { ThemeOptions, Theme } from '@material-ui/core/styles/createMuiTheme';

import { PaletteOptions } from '@material-ui/core/styles/createPalette';

interface IPaletteOptions extends PaletteOptions {

chip: {

color: string,

expandIcon: {

background: string,

color: string,

},

},

}

interface ITheme extends Theme {

palette: IPaletteOptions,

}

const theme: ITheme = createMuiTheme({

typography: {

fontWeightMedium: 600,

fontFamily: ['Open Sans', 'Arial', 'sans-serif'].join(','),

},

palette: {

primary: {

main: '#43C099',

},

secondary: {

main: '#7AF3CA',

},

chip: {

color: '#C2C3C6',

expandIcon: {

background: '#808183',

color: '#FFFFFF',

},

},

},

} as ThemeOptions);

这会引发错误,

Type 'Theme' is not assignable to type 'ITheme'.

Types of property 'palette' are incompatible.

Property 'chip' is missing in type 'Palette' but required in type 'IPaletteOptions

对我来说这是一个令人困惑的错误,因为类型I不在Palette任何地方使用该类型。

如何在此处适当扩展调色板?

回答:

import createMuiTheme, { Theme, ThemeOptions } from "@material-ui/core/styles/createMuiTheme";

import { Palette } from "@material-ui/core/styles/createPalette";

interface IPalette extends Palette {

xxx: {}

}

interface ITheme extends Theme {

palette: IPalette;

}

interface IThemeOptions extends ThemeOptions {

palette: IPalette;

}

const theme = createMuiTheme({

palette: {

...

xxx: {} // Type been checked

}

} as IThemeOptions) // Use customized ThemeOptions type

const useStyles = makeStyles((theme: ITheme) => ({ // Use customized Theme type

root: {

color: theme.palette.xxx // Work with no type error

}

}));


参考

如果我们看一下createMuiTheme.d.ts

import { Palette, PaletteOptions } from './createPalette';

export interface ThemeOptions {

palette?: PaletteOptions;

...

}

export interface Theme {

palette: Palette;

...

}

export default function createMuiTheme(options?: ThemeOptions, ...args: object[]): Theme;

我们会发现这一点,ThemeThemeOptions发挥不同的作用。

  • 主题:返回类型
  • ThemeOptions:参数类型

以上是 如何使用Typescript扩展Material-UI主题? 的全部内容, 来源链接: utcz.com/qa/410925.html

回到顶部