如何使用 TypeScript 在 Material UI 上添加自定义颜色名称?

Fra*_*tin 8 typescript reactjs material-ui

我正在使用 TypeScript 使用 Material UI,并希望向我的主题添加自定义颜色。一切工作正常,除了 VSCode linter 向我显示下一条消息。

Type '{ tan: string; lightRed: string; red: string; offBlack: string; white: string; }' is not assignable to type 'Partial<CommonColors>'.
  Object literal may only specify known properties, and 'tan' does not exist in type 'Partial<CommonColors>'.
Run Code Online (Sandbox Code Playgroud)

在开发和构建方面工作正常,唯一的抱怨是错误消息。我添加了一个自定义类型来尝试解决,但它不起作用。

Type '{ tan: string; lightRed: string; red: string; offBlack: string; white: string; }' is not assignable to type 'Partial<CommonColors>'.
  Object literal may only specify known properties, and 'tan' does not exist in type 'Partial<CommonColors>'.
Run Code Online (Sandbox Code Playgroud)
const theme = createTheme({
  palette: {
    common: {
      tan,
      lightRed,
      red,
      offBlack,
      white,
    },
  },
});
Run Code Online (Sandbox Code Playgroud)

我添加到tsconfig.json文件中。tan、red 和其余值被声明为字符串。关于如何解决这个问题有任何线索吗?提前致谢。

Rya*_*ell 16

我不能声称对模块增强有很好的理解,但我已经在自己的应用程序中完成了它(也适用于调色板中的自定义颜色),并且当我使用与我自己的应用程序中相同的方法时,它适用于您的场景。我的理解是,您只需要指定增强 - 您不需要创建扩展现有类型的新类型。就您而言,您只想增强CommonColors.

以下方法似乎有效:

import "@mui/material/styles/createPalette";
declare module "@mui/material/styles/createPalette" {
  interface CommonColors {
    tan: string;
    lightRed: string;
    red: string;
    offBlack: string;
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑 TypeScript 自定义颜色

在我的示例中,我将此代码放在一个createPalette.d.ts文件中,该文件的名称似乎很重要(尽管它位于哪个目录似乎并不重要,只要它位于编译器查看的目录中即可)。将代码直接放入index.tsx或直接放入执行的 TypeScript 文件中也可以正常工作createTheme

相关回答: