如何使用TypeScript在物料UI上添加自定义颜色名称? [英] How to add custom colors name on Material UI with TypeScript?

查看:35
本文介绍了如何使用TypeScript在物料UI上添加自定义颜色名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有TypeScript的材料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>'.

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

const theme = createTheme({
  palette: {
    common: {
      tan,
      lightRed,
      red,
      offBlack,
      white,
    },
  },
});
import {
  PaletteOptions,
  CommonColors,
} from '@material-ui/core/styles/createPalette';

interface CustomColors extends CommonColors {
  tan: string?;
  lightRed: string;
  red: string;
  offBlack: string;
}

declare module '@material-ui/core/styles/createPalette' {
  export interface PaletteOptions {
    common: CustomColors;
  }
}

我添加到tsconfig.json文件。黄褐色、红色和睡觉的值被声明为字符串。我怎么才能解决这个问题有什么线索吗?提前谢谢。

推荐答案

我不能说对模块增强有很好的理解,但我已经在我自己的应用程序中做到了这一点(调色板中的自定义颜色也是如此),当我使用与我自己的应用程序中相同的方法时,它适用于您的方案。我的理解是,您只需指定扩展--不需要创建扩展现有类型的新类型。在您的情况下,您只需要增加CommonColors

以下方法似乎有效:

import "@mui/material/styles/createPalette";
declare module "@mui/material/styles/createPalette" {
  interface CommonColors {
    tan: string;
    lightRed: string;
    red: string;
    offBlack: string;
  }
}

在我的示例中,我将此代码放在一个createPalette.d.ts文件中,该文件的名称似乎并不重要(不过,只要它位于编译器所查看的目录中,它位于哪个目录似乎并不重要)。也可以将代码直接放入index.tsx或直接放入执行createTheme的类型脚本文件中。

相关答案:

这篇关于如何使用TypeScript在物料UI上添加自定义颜色名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆