You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic React+TypeScript中map参数item隐式any类型报错如何解决

错误原因

你之前的两种写法不符合TypeScript箭头函数的类型注解语法:当你需要给单个箭头函数参数加类型声明时,必须把参数包裹在圆括号内,否则TS无法识别语法,报错无法避免。

临时解决方案(用any)

只需要给参数加圆括号包裹即可:

{items.map((item: any) => {
  return (
    <IonSegmentButton key={item.id}>
      <IonLabel>{item.value}</IonLabel>
    </IonSegmentButton>
  )
})}

规范解决方案(不推荐用any,定义明确类型)

首先先定义你的数据项类型:

interface SegmentItem {
  id: number;
  value: string;
}

给useLocalStorage hook加上泛型约束,这样items会被自动推断为SegmentItem[]类型,后续map时不需要额外给item加类型注解:

const [items, setItems] = useLocalStorage<SegmentItem[]>(
  [{ 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>

内容的提问来源于stack exchange,提问作者Phill Healey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:15:05