Reactjs 向调色板添加自定义颜色可能会导致对象“未定义”。TS2532

Reactjs 向调色板添加自定义颜色可能会导致对象“未定义”。TS2532,reactjs,typescript,material-ui,Reactjs,Typescript,Material Ui,我正在尝试向材质ui调色板添加新的自定义颜色,我知道它将与4.1一起发布,但这在将来会被删除 我是打字新手,所以我很难弄清楚该怎么做才能让它工作 我遵循了Amential ui文档中的指南,并提出了这一点 import createMuiTheme, { ThemeOptions } from '@material-ui/core/styles/createMuiTheme'; declare module '@material-ui/core/styles/createPalette' {

我正在尝试向材质ui调色板添加新的自定义颜色,我知道它将与4.1一起发布,但这在将来会被删除

我是打字新手,所以我很难弄清楚该怎么做才能让它工作

我遵循了Amential ui文档中的指南,并提出了这一点

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

declare module '@material-ui/core/styles/createPalette' {
  interface Palette {
    warning?: PaletteColor
    success?: PaletteColor
  }

  interface PaletteOptions {
    warning?: PaletteColorOptions
    success?: PaletteColorOptions
  }
}

export default function createMyTheme(options: ThemeOptions) {
  return createMuiTheme({
    ...options,
  })
}
使用它的时候呢

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

const styles = (theme: Theme) => createStyles({
  success: {
    backgroundColor: theme.palette.success.main,
  },
  error: {
    backgroundColor: theme.palette.error.dark,
  },
  info: {
    backgroundColor: theme.palette.primary.dark,
  },
  warning: {
    backgroundColor: theme.palette.warning.main,
  },
});
连接到具有withStyles HOC的组件

我得到的只是控制台中的这个错误

Object is possibly 'undefined'.  TS2532
指向背景色:theme.palete.success.main

有人这样做了吗?

您不必使调色板属性成为可选的-假定它们将具有一些默认值(如果没有被选项覆盖的话)。将其描述更改为以下内容:

interface Palette {
  warning: PaletteColor
  success: PaletteColor
}
一切都应该很好