Home > Mobile >  No index signature with a parameter of type 'string' Error in TypeScript while giving type
No index signature with a parameter of type 'string' Error in TypeScript while giving type

Time:11-28

I was converting my ReactJS app written in JS to Typescript.

I am getting this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'topBarType'. No index signature with a parameter of type 'string' was found on type 'topBarType'.

type topBarType = {
    height: string;
    "font-size": string;
    iconWidth: string;
    iconHeight: string;
};
type variantTypes = 'sm'|'md'|'lg';

export function topBarTheme(variant: variantTypes, property: string): string {
    const theme: { [key: string]: topBarType } = {
        sm: {
            height: `height:2rem;`,
            "font-size": `font-size: 1.5rem;`,
            iconWidth: `width: 1.75rem;`,
            iconHeight: `height: 1.75rem;`,
        },
        md: {
            height: `height:2.5rem;`,
            "font-size": `font-size: 1.75rem;`,
            iconWidth: `width: 2rem;`,
            iconHeight: `height: 2rem;`,
        },
        lg: {
            height: `height:3rem;`,
            "font-size": `font-size: 2rem;`,
            iconWidth: `width: 2.5rem;`,
            iconHeight: `height: 2.5rem;`,
        },
    };

    if (!variant) return theme["lg"][property]; <-- Error
    return theme[variant][property]; <-- Error
}

CodePudding user response:

Try defining the type for the property argument:

type topBarProperties = keyof topBarType;

export function topBarTheme(
  variant: variantTypes,
  property: topBarProperties
): string {
...
  • Related