Expo Action Sheet类型错误:回调参数类型不匹配引发类型冲突
解决Expo Action Sheet的TypeScript类型错误
问题根源
你遇到的第一个类型错误,核心是回调函数的参数类型不匹配:showActionSheetWithOptions的回调参数允许是number | undefined(用户可能未选择任何选项就关闭弹窗,此时会传undefined),但你把参数定义成了必填的number,导致TypeScript报错。
第二个错误是因为你尝试手动指定返回类型时写法有误——async函数本身就会自动返回Promise<void>,不需要额外画蛇添足。
修复方案
- 修正回调参数类型:把
selectedIndex的类型改为number | undefined,或者直接用可选参数selectedIndex?: number,同时在逻辑里处理undefined的情况。 - 移除多余的返回类型声明: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
相关产品推荐
相关产品推荐

