如何解决 Material UI 5 中自定义主题中的打字稿错误?

Nat*_*amy 5 typescript reactjs material-ui

我们有palette.ts它包含变量中的所有颜色属性palette并导出。我们导入palette.tsthemeProvider.tsx使用。但由于自定义属性,我们收到打字稿错误,如下图所示。有什么方法可以定义自定义属性的类型吗?

palette.ts

import { alpha } from '@mui/material/styles';

const palette = {
  common: { black: '#000', white: '#fff' },
  primary: { ...PRIMARY },
  secondary: { ...SECONDARY },
  info: { ...INFO },
  success: { ...SUCCESS },
  warning: { ...WARNING },
  error: { ...ERROR },
  grey: GREY,
  gradients: GRADIENTS,
  chart: CHART_COLORS,
  divider: GREY[500_24],
  text: { primary: GREY[800], secondary: GREY[600], disabled: GREY[500] },
  background: { paper: '#fff', default: GREY[100], neutral: GREY[200] },
  action: {
    active: GREY[600],
    hover: GREY[500_8],
    selected: GREY[500_16],
    disabled: GREY[500_80],
    disabledBackground: GREY[500_24],
    focus: GREY[500_24],
    hoverOpacity: 0.08,
    disabledOpacity: 0.48,
  },
  custom: {
    iconBorderRadius: 1,
    iconBorderRadius2: 0.5,
  },
};

export default palette;
Run Code Online (Sandbox Code Playgroud)

themeProvider.tsx

import { createTheme, CssBaseline } from '@mui/material';
import {
  StyledEngineProvider, ThemeProvider as MUIThemeProvider
} from '@mui/material/styles';
import React, { useMemo } from 'react';
import componentsOverride from './overrides';
import palette from './palette';
import shadows, { customShadows } from './shadows';
import typography from './typography';

export default function ThemeProvider({ children }) {
  const themeOptions = useMemo(
    () => ({
      palette,
      shape: { borderRadius: 8 },
      typography,
      shadows,
      customShadows,
    }),
    []
  );
  const theme = createTheme(themeOptions);
  theme.components = componentsOverride(theme);

  return (
    <StyledEngineProvider injectFirst>
      <MUIThemeProvider theme={theme}>
        <CssBaseline />
        {children}
      </MUIThemeProvider>
    </StyledEngineProvider>
  );
}
Run Code Online (Sandbox Code Playgroud)

Usage typescript error

在此输入图像描述

小智 1

正如 mui.com 所说:“如果您使用 TypeScript,您还需要使用主题的模块增强来接受上述值。”

因此,对于您的情况,您需要将这些行添加到您的palette.ts

interface CustomPalettes {
  custom: {
    iconBorderRadius: number;
    iconBorderRadius2: number;
  };
}
declare module '@mui/material/styles' {
  interface PaletteOptions extends CustomPalettes {}
}
declare module '@mui/material/styles/createPalette' {
  interface Palette extends CustomPalettes {}
}
Run Code Online (Sandbox Code Playgroud)