skip to Main Content

enter image description here
enter image description here

set function -> meun parameter error!
error = > Parameter ‘menu’ implicitly contains the form ‘any’
typescript index signature
Is it an error related to type script index signature?
Help me

2

Answers


  1. You have to define a typefor the menu parameter. Because typescript cannot allow you to iterate through a value if it does not know if that value is an array. You can create a type like this.

    {menu:Array<{a:string,b:number,c:boolean}>}
    

    You have to assign the type to menu before you use it anywhere in the component.I you’re lazy to define the object inside (which you shouldn’t be) or if the array can contain different types of elements, you can do this

    {menu:Array<{any}>}
    
    Login or Signup to reply.
  2. So your data structure could use some evaluation. Typescript can actually help you think through this.

    menu is an array of objects, but those objects can be Category objects or Module objects. Can there be other types? Let’s revisit this shortly.

    I see there is a common shape to the Category and Module objects. They are arrays of objects with the same pattern, {value: 1, text: 'some value'} so let’s make a type for this.

    type LabelAndValue = {
      value: number,
      text: string
    

    So now how do we describe Category and Module? They are arrays of LabelAndValues. We can describe that as Array<LabelAndValue> or LabelAndValue[] in type script.

    Category : Array<LabelAndValue>,
    Module : Array<LabelAndValue>,
    

    Now we get to the tricky part.

    Menu is an array of objects, that can either take the shape Category : Array<LabelAndValue>, Module : Array<LabelAndValue>,

    So if I had the choice in shaping my object, I would get rid of the array of objects entirely. I would just make menu an object that has a "Category" and a "Module" array. You can directly access these keys from menu instead of having to loop over menu.

    menu = {
      "Category" : [],
      "Module" : [],
    
    }
    

    In TypeScript we can describe this as

    type Menu : {
      Category : Array<LabelAndValue>,
      Module : Array<LabelAndValue>,
    }
    

    However, if we need to keep the shape of your menu, we can do assume there is only ever two types of menus category or modules.

    type menu = Array<{Category: Array<LabelAndValue>} | {Module: Array<LabelAndValue>}>
    

    Or we can assumes these objects can have any string key, but are always of the LabelAndValue shape

    type Menu = Array<{[key: string]: Array<LabelAndValue>}>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search