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
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.
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
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 beCategory
objects orModule
objects. Can there be other types? Let’s revisit this shortly.I see there is a common shape to the
Category
andModule
objects. They are arrays of objects with the same pattern,{value: 1, text: 'some value'}
so let’s make a type for this.So now how do we describe
Category
andModule
? They are arrays of LabelAndValues. We can describe that asArray<LabelAndValue>
orLabelAndValue[]
in type script.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.
In TypeScript we can describe this as
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.
Or we can assumes these objects can have any string key, but are always of the
LabelAndValue
shape