【问题标题】:Expo Action Sheet gives type error, can't assign return type Promise<void> to type of void | Promise<void>Expo Action Sheet 给出类型错误,无法将返回类型 Promise<void> 分配给 void 类型 |承诺<无效>
【发布时间】:2022-12-11 12:58:01
【问题描述】:

这是我用来显示世博会文档的操作表基础的代码: https://github.com/expo/react-native-action-sheet

takePicture 和 pickImage 函数都有类型签名: () =&gt; Promise&lt;null | undefined&gt;

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

showActionSheetWithOptions(
  { options, cancelButtonIndex },
  async (selectedIndex: number) => {
    switch (selectedIndex) {
      case 0:
        console.log("taking photo")
        await takePicture()

        break
      case 1:
        console.log("uploading from gallery")
        await pickImage()
        break

      case cancelButtonIndex:
      // Canceled
    }
  }
)

我相信我的代码与文档匹配,但我收到以下类型错误:

Argument of type '(selectedIndex: number) => Promise<void>' is not assignable to parameter of type '(i?: number | undefined) => void | Promise<void>'.
  Types of parameters 'selectedIndex' and 'i' are incompatible.
    Type 'number | undefined' is not assignable to type 'number'.
      Type 'undefined' is not assignable to type 'number'.ts(2345)

我尝试引入虚拟 Promises 以使选择器函数匹配正确的类型签名,但我得到了不同的类型错误,The return type of an async function or method must be the global Promise&lt;T&gt; type. Did you mean to write 'Promise&lt;void&gt;'?ts(1064)

我觉得我错过了一些明显的东西,但我不知道是什么。非常感谢任何帮助。

【问题讨论】:

    标签: typescript react-native expo


    【解决方案1】:

    删除回调函数中 selectedIndex 的类型提示修复了错误。正确的类型是number | undefined

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      相关资源
      最近更新 更多