javascript - 如何从Typescript中的回调中获取返回值的类型

标签 javascript typescript firebase types

我有一段代码是这样的:

validateViaTransaction(
  id: string,
  datas: any,
  callback: <T> (t: firestore.Transaction, data: any) => Promise<T>
) => {
  return await firestore().
   runTransaction(async t => {
    get someting...

    validate something and throw err...

    return await callback(t, data);

   }).catch(err => { throw err; });
}

现在当我稍后尝试使用时:

await validateViaTransaction(id, null, (t: firestore.Transaction) => {
 t.set(new data here...., {merge: true});

 return "Validation Successful";
})

现在,当我检查代码的返回类型时,它是 Promise <unknown>

当我在代码中实现它时,错误是这样的。

Argument of type '(t: Transaction) => string' is not assignable to parameter of type '<T>(t: Transaction, data: any) => T'.
  Type 'string' is not assignable to type 'T'.
    'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.ts(2345)

有没有办法让我的callback功能更像通用的?就像我回来后 string 那么它的类型也将是 string

最佳答案

您正在调用这样的回调:return await callback(t, data);

通过使用 await callback预计返回 Promise (你只能等待 promise )

您需要为此调整您的签名:

callback: <T> (t: firestore.Transaction, data: any) => Promise<T>

通过使用 async在功能上,它将自动包装在 promise 中。

所以你应该这样调用它:

await validateViaTransaction(id, null, async (t: firestore.Transaction) => {
 t.set(new data here...., {merge: true});

 return "Validation Successful";
})

有了异步,回调现在将返回 Promise<string>

关于javascript - 如何从Typescript中的回调中获取返回值的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56804314/

相关文章:

firebase - 如何使用 Admin API 在 Firebase Storage 中创建文件夹

javascript - Javascript时间与给定时间进行比较

javascript - 从 Javascript 文件对象添加属性时处理文件上传

javascript - 如何保持 Spring 表单中选定的值 :options?

javascript 和 css 加载

javascript - 映射根据 Typescript 中的键类型设置不同类型的值

typescript - 什么是 typescript `--lib` 库文件?

java - 如何将倒计时器添加到 Firebase 中?

javascript - 逐渐从包含每个 JS 文件转向模块捆绑

firebase - 无法使用(com.firebase.ui.storage.images.FirebaseImageLoader)解析方法