1

I'm trying to learn Ionic React with Typescript by creating a simple app for myself.

At this point 'I'm trying to dynamically populate an IonSegment from an array, the relevant code looks like this:

const [items, setItems] = useLocalStorage([{ id: 0, value: 'Item 0' }, { id: 1, value: 'Item 1' }, { id: 1, value: 'Item 1' }], [{ id: 0, value: 'An Error Occurred' }]);

....

<IonSegment color="brand" onIonChange={ ....... } value={sensor} id="segSensor">
            {items.map(item => {
              return (
                <IonSegmentButton key={item.id}>
                  <IonLabel>{item.value}</IonLabel>
                </IonSegmentButton>
              )
            })}
</IonSegment>

This fails to compile with the output:

Parameter 'item' implicitly has an 'any' type.ts(7006)

So, I understand that item needs to have a type declared, but I've tried the following without success:

{items.map(item:any => {
              return (

{items.map(<any>item => {
              return (

How do I declare the type for item?

Thanks

Phill Healey
  • 3,084
  • 2
  • 33
  • 67

3 Answers3

5

Well its simple, you have to enclose your input in parenthesis as

items.map((item: any) => {})

Another thing that you can do is go in your tsconfig.json file and set noImplicityAny to false. This will stop TypeScript from yelling at you if something has an implicit any type.

aekant
  • 199
  • 1
  • 5
  • I'd read about the noImplicitAny flag but figured I'd leave it as is inorder to force me to learn things like this. – Phill Healey Nov 12 '21 at 10:04
3

items.map((item: any) => { ...

Probably the problem is in useLocalStorage type too, maybe you have to create a type/interface for your initial state

useLocalStorage<MyLocalStorageType>( ...

Like that you can use the full power of TS

robb
  • 114
  • 4
2

You are missing the paranteses in the arrow function when declaring a type:

{items.map((item: any) => {
              return (
moiri
  • 41
  • 5