我想在 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/