0

I am trying to access a nested object structure using object keys, but TypeScript gives me the error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type...

My color themes object structure is as follows:

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: {
        ...;
    };
}

But when I am accessing the color, it shows me the error. Please help. I am not able to access the themes.colors[color][weight] Error: enter image description here

0

1 Answer 1

1

One option would be to define the colors object as a record type:

colors: Record<string, any> = {
    background: string;
    text: string;
    black: string;
    ...
};

Or use a typecast on the index key:

export const getColor = (color: string, weight: number, alpha = 1) => {
  const theme = useTheme();
  return hexToRgba(theme.colors[color as keyof typeof theme.colors][weight], alpha);
};

Another option, would be to use a typecast on the colors object:

export const getColor = (color: string, weight: number, alpha = 1) => {
  const theme = useTheme();
  return hexToRgba((theme.colors as {[key: string]: any})[color][weight], alpha);
};

See Stack Overflow question Typescript Error: type 'string' can't be used to index type X.

Sign up to request clarification or add additional context in comments.

2 Comments

@DhruvKothari If you want precise type checking, then you could define a ThemeColors interface or a ThemeColors type. This would be especially appropriate if you use the theme colors in several places in your app. If, however, the theme colors are only used in one or two places, then using any is probably ok.
@DhruKothari If this answer solved your problem, could you mark it as the accepted answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.