Typescript接口与Firestore查询的一致性

Typescript接口与Firestore查询的一致性

本文介绍了Typescript接口与Firestore查询的一致性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Firebase和我自己的Typescript接口?

How do I work with Firebase and my own Typescript interfaces?

即.我在这里有一个函数,我需要完整的 Payment 对象(不仅是增量),因此我可以通过 DocumentReference 对象.

ie. I have a function here that I'm going to need the full Payment object, (not just the delta), so I get that via the DocumentReference object.

function doSomethingWithPayment(payment: Payment) {
   console.log(payment.amount);
}


exports.resolveStripeCharge = functions.firestore.document('/payments/{paymentId}')
    .onWrite((change : Change <DocumentSnapshot>) => {

        change.after.ref.get().then((doc: DocumentSnapshot )=> {
            const payment : Payment =   doc.data(); // tslint warning here.
            doSomethingWithPayment(payment);

        })


[ts]
Type 'DocumentData' is not assignable to type 'Payment'.
  Property 'amount' is missing in type 'DocumentData'.
const payment: Payment

我得到返回的对象不一定符合接口的要求-但无论如何-如果我要强制键入内容,我应该在这里做什么?

I get that the returned object wont necessarily conform the interface - but in anycase -what should I do here - if I want to enforce typing?

我只使用:

 const payment : Payment =   <Payment>doc.data();

还是有更好的解决方案?

Or is there a much nicer solution?

推荐答案

所以,我的建议是,只需使用:

So, what I would suggest is, just use :

常量付款= doc.data()

如果是 const ,则将自动强制键入.

In case of const, the typing will be automatically enforced.

OR

这篇关于Typescript接口与Firestore查询的一致性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:57