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

Expo Action Sheet类型错误:回调参数类型不匹配引发类型冲突

解决Expo Action Sheet的TypeScript类型错误

问题根源

你遇到的第一个类型错误,核心是回调函数的参数类型不匹配:showActionSheetWithOptions的回调参数允许是number | undefined(用户可能未选择任何选项就关闭弹窗,此时会传undefined),但你把参数定义成了必填的number,导致TypeScript报错。

第二个错误是因为你尝试手动指定返回类型时写法有误——async函数本身就会自动返回Promise<void>,不需要额外画蛇添足。

修复方案

  1. 修正回调参数类型:把selectedIndex的类型改为number | undefined,或者直接用可选参数selectedIndex?: number,同时在逻辑里处理undefined的情况。
  2. 移除多余的返回类型声明:async函数默认返回Promise<void>,不需要手动添加虚拟Promise或者错误的类型声明。

修复后的代码

const options = ["Take Photo", "Upload From Library", "Cancel"]
const cancelButtonIndex = 2

showActionSheetWithOptions(
  { options, cancelButtonIndex },
  async (selectedIndex?: number) => {
    // 先处理未选择或取消的情况
    if (selectedIndex === undefined || selectedIndex === cancelButtonIndex) {
      return
    }

    switch (selectedIndex) {
      case 0:
        console.log("taking photo")
        await takePicture()
        break
      case 1:
        console.log("uploading from gallery")
        await pickImage()
        break
    }
  }
)

补充说明

  • 为什么参数会是undefined?当用户点击弹窗外部(如果支持的话)或者某些平台上的取消操作,Action Sheet可能不会传递有效索引,此时参数就是undefined,所以必须处理这种情况。
  • 如果你不想处理undefined,也可以用类型断言,但不推荐(因为可能会忽略边界情况):把参数声明改成async (selectedIndex) => { const index = selectedIndex as number; ... },但这样会跳过TypeScript的类型检查,存在风险。

内容的提问来源于stack exchange,提问作者Gus Beringer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:50:38