我试图使用对象键访问嵌套的对象结构,但是TypeScript给出了错误:
元素隐式具有“任意”类型,因为“string”类型的表达式不能用于索引类型.
我的颜色主题对象结构如下:
colors: {
background: string;
text: string;
black: string;
white: string;
yellow: {
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
};
green: {
100: string;
... 7 more ...;
900: string;
};
red: {
...;
};
cyan: {
...;
};
purple: {
...;
};
gray: {
...;
};
}但是当我访问颜色时,它会显示错误。请帮帮忙。我无法访问themes.colorscolor错误:

发布于 2021-11-13 20:59:56
一种选择是将colors对象定义为记录类型:
colors: Record<string, any> = {
background: string;
text: string;
black: string;
...
};或者在索引键上使用类型设置:
export const getColor = (color: string, weight: number, alpha = 1) => {
const theme = useTheme();
return hexToRgba(theme.colors[color as keyof typeof theme.colors][weight], alpha);
};另一种选择是对colors对象使用类型广播:
export const getColor = (color: string, weight: number, alpha = 1) => {
const theme = useTheme();
return hexToRgba((theme.colors as {[key: string]: any})[color][weight], alpha);
};参见堆栈溢出问题Typescript Error: type 'string' can't be used to index type X。
https://stackoverflow.com/questions/69958074
复制相似问题