首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >没有使用React组件的“string”参数的索引签名。

没有使用React组件的“string”参数的索引签名。
EN

Stack Overflow用户
提问于 2021-11-13 20:41:05
回答 1查看 232关注 0票数 0

我试图使用对象键访问嵌套的对象结构,但是TypeScript给出了错误:

元素隐式具有“任意”类型,因为“string”类型的表达式不能用于索引类型.

我的颜色主题对象结构如下:

代码语言:javascript
复制
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错误:

EN

回答 1

Stack Overflow用户

发布于 2021-11-13 20:59:56

一种选择是将colors对象定义为记录类型:

代码语言:javascript
复制
colors: Record<string, any> = {
    background: string;
    text: string;
    black: string;
    ...
};

或者在索引键上使用类型设置:

代码语言:javascript
复制
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对象使用类型广播:

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69958074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档