typescript - Material UI v4 : extending PaletteColorOptions

标签 typescript material-ui

我想在 Material UI v4 (v4.11) 调色板中做一些非常简单的事情:向 PaletteColorOptions 添加一个新字段。假设我想添加 darker?: string

这是相关 Material UI 模块中的类型定义:

createPalette.d.ts

export type PaletteColorOptions = SimplePaletteColorOptions | ColorPartial;

export interface SimplePaletteColorOptions {
  light?: string;
  main: string;
  dark?: string;
  contrastText?: string;
}

a merged PR to Material UI它在他们的文档中添加了如何通过模块增强添加新的调色板颜色选项的示例。这是他们的建议:

declare module '@material-ui/core/styles/createMuiTheme' {
  interface PaletteColor {
    darker?: string
  }
  interface SimplePaletteColorOptions {
    darker?: string
  }
}

我尝试了这个,但它似乎不起作用 - 当我尝试将 darker 添加到其中一个颜色对象时,我收到以下错误 - 表明我没有设法添加PaletteColorOptions 的新字段

Type '{ dark: string; main: string; contrastText: string; darker: string; }' is not assignable to type 'PaletteColorOptions | undefined'. Object literal may only specify known properties, and 'darker' does not exist in type 'PaletteColorOptions'.ts(2322) createPalette.d.ts(105, 3): The expected type comes from property 'primary' which is declared here on type 'PaletteOptions'

我还尝试向 createPalette 模块添加类似的定义(再次通过上面示例中建议的模块扩充),但我收到了与上面所示相同的 TypeScript 错误。

declare module '@material-ui/core/styles/createPalette' {
  interface PaletteColor {
    darker?: string
  }
  interface PaletteColorOptions {
    darker?: string
  }
}

如有任何指导,我们将不胜感激。

最佳答案

最后我成功解决了这个问题。我是这样做的:

palette.ts(我们创建的用于定义调色板的文件)

interface ExtendedPaletteColorOptions extends SimplePaletteColorOptions {
  darker?: string
}

interface ExtendedPaletteOptions extends PaletteOptions {
  primary: ExtendedPaletteColorOptions
  secondary: ExtendedPaletteColorOptions
  text: Partial<TypeText>
  error: ExtendedPaletteColorOptions
  warning: ExtendedPaletteColorOptions
  info: ExtendedPaletteColorOptions
  success: ExtendedPaletteColorOptions
  // And your custom palette options if you defined them, e.g:
  // brand: ExtendedPaletteColorOptions
}

const palette: ExtendedPaletteOptions = {
  // Our palette, which now supports the new `lighter`, for example:
  primary: {
    main: '#555555',
    dark: '#333333',
    darker: '#111111',
  }
}

theme.d.ts(我们为material-ui模块的模块增强而创建的文件)

declare module '@material-ui/core/styles/createPalette' {
  interface PaletteColor {
    lighter: string
  }
}

关于typescript - Material UI v4 : extending PaletteColorOptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69514804/

相关文章:

javascript - 如何以 Angular 对html表的每一行进行组件化

angular - 如何使用 angular2 在正文上附加内容

javascript - 即使从 ts 编译为 js 后如何保持类型安全

angular - 如何计算 Angular 6中keyup中的字符

typescript - TsLint: '$http' 不能在构造函数中声明

reactjs - 使用示例响应式抽屉时 Material UI 表没有响应

reactjs - Material UI 选择覆盖主题中的位置

java - 错误膨胀类 com.google.android.material.button.MaterialButton

reactjs - 如何屏蔽我的 Material-UI 文本字段?

material-ui - 选择能够写入自定义值的组件