打字稿模块扩充不起作用:属性 'main' 在类型 'PaletteColorOptions' 上不存在

Typescript Module augmentation is not working: Property 'main' does not exist on type 'PaletteColorOptions'

我一直在研究 Material-UI 并尝试在整个调色板中使用颜色系统。编译时似乎有一些问题,尽管它在 运行 时间内运行良好。谁能帮我解决以下错误:

错误:

Property 'main' does not exist on type 'PaletteColorOptions'.
Property 'main' does not exist on type 'Partial'.(2339)

这里还有 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>
  );
}

TypeScript 错误与您的模块扩充无关。问题只是 defaultColors 的类型是 PaletteOptionsPaletteOptions 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;
}

因此 TypeScript 编译器知道 defaultColors.primarySimplePaletteColorOptions ColorPartial,但它不知道是哪个。然后您将引用 defaultColors.primary.main,但不能保证存在,除非 defaultColors.primary 的类型是 SimplePaletteColorOptions

您可以通过为 Default 函数使用更具体的 return 类型来解决此问题,让 TypeScript 知道 primary 的类型是 SimplePaletteColorOptions:

interface DefaultPaletteOptions extends PaletteOptions {
  primary?: SimplePaletteColorOptions;
}
const Default = (): DefaultPaletteOptions => {
  return {
    primary: {
      lighter: "#ddd",
      light: "#ddd",
      main: "#ddd",
      dark: "#ddd",
      darker: "#ddd"
    }
  };
};

相关回答: