Home > OS >  Element implicitly has an 'any'. typescript error
Element implicitly has an 'any'. typescript error

Time:05-11

const getActiveMenu = (path: string) => {
    const headerkey = {
        "admin": "admin",
        "pdesk":"pdesk"
    }

    const pathArray = path.split("/")

    return headerkey[pathArray[1]]                                                 
}                                                                               
export {getActiveMenu};

typescript error is that => Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ admin: string; pdesk: string; }'.
No index signature with a parameter of type 'string' was found on type '{ admin: string; pdesk: string; }'.

CodePudding user response:

typeof pathArray is string[], that is issue

const getActiveMenu = (path: string) => {
  const headerkey = {
    admin: "admin",
    pdesk: "pdesk",
  };

  type KeyType = keyof typeof headerkey;
  const pathArray = path.split("/") as KeyType[];
  const key = pathArray[1];

  return headerkey[key];
};
export { getActiveMenu };

CodePudding user response:

Typescript's basically complaining that string is too broad as a key for your headerKey object and it can't infer what the type should be for the key and so it is implicitly considered an 'any' type as a result of that.

In addition to the other answer (of casting the type) You can do one of the following to avoid this becoming an issue in your typescript/react projects:

  1. Update your tsconfig to ignore implicit any error reporting, if you're okay with it

Add this to your tsconfig.json

    "noImplicitAny": false,

https://www.typescriptlang.org/tsconfig#noImplicitAny

  1. If you don't want to do that, in your code you can define a broad type for the map's keys to give it a valid index signature
const headerkey : {[key: string]: string} = {
    admin: "admin",
    pdesk: "pdesk",
  };
  • Related