[英]Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Palette'
I'm getting我越来越
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Palette'.
No index signature with a parameter of type 'string' was found on type 'Palette'.ts(7053)
While trying to use a list of strings to get themes from the ThemeProvider
from Material-UI尝试使用字符串列表从 Material-UI 的ThemeProvider
获取主题时
swatches is a string[]
and contains strings that looks like "primary.light"
or "secondary.dark"
swatches 是一个string[]
并且包含看起来像"primary.light"
或"secondary.dark"
的字符串
useTheme
uses this file: useTheme
使用这个文件:
import { createTheme, responsiveFontSizes } from '@mui/material/styles';
import { deepPurple, amber } from '@mui/material/colors';
// Create a theme instance.
let theme = createTheme({
palette: {
primary: deepPurple,
secondary: amber,
},
});
theme = responsiveFontSizes(theme);
export default theme;
and the component:和组件:
const ColorPaletteContent = ({ content }: { content: ColorPalette }) => {
const theme = useTheme();
return (
<>
<h1>{content.title}</h1>
<div className={colorPaletteStyles.swatch_container}>
{content.swatches.map((swatch) => {
const parentColor = swatch.split('.')[0];
const childColor = swatch.split('.')[1];
return (
<div key={swatch} className={colorPaletteStyles.swatch}>
<Avatar
sx={{
bgcolor: theme.palette[parentColor][childColor],
height: 68,
width: 68,
}}
>
{''}
</Avatar>
{childColor}
</div>
);
})}
</div>
</>
);
};
The Palette
interface looks like this, so I know that using a string as key here is invalid, but how do I cast my parentColor
and childColor
accordingly so that the type is correct?: Palette
接口看起来像这样,所以我知道在这里使用字符串作为键是无效的,但是我如何相应地转换我的parentColor
和childColor
以便类型正确?:
export interface Palette {
common: CommonColors;
mode: PaletteMode;
contrastThreshold: number;
tonalOffset: PaletteTonalOffset;
primary: PaletteColor;
secondary: PaletteColor;
error: PaletteColor;
warning: PaletteColor;
info: PaletteColor;
success: PaletteColor;
grey: Color;
text: TypeText;
divider: TypeDivider;
action: TypeAction;
background: TypeBackground;
getContrastText: (background: string) => string;
augmentColor: (options: PaletteAugmentColorOptions) => PaletteColor;
}
parentColor
is any
, not a keyof Palette
. parentColor
是any
,而不是Palette
的键。 To remove the error, you need to assert it with the correct type:要消除错误,您需要使用正确的类型对其进行断言:
// "primary" | "secondary" | "error" | "warning" | "info" | "success"
type PaletteKey = keyof {
[Key in keyof Palette as Palette[Key] extends PaletteColor ? Key : never]: true;
}
// "light" | "dark" | "main" | "contrastText"
type PaletteColorKey = keyof PaletteColor
theme.palette[parentColor as PaletteColorKey][childColor as PaletteColorKey]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.