我有一段代码是这样的:
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/