Resolving typescript
Resolving typescript
How do I work with Firebase and my own Typescript interfaces?
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.
Payment
DocumentReference
exports.resolveStripeCharge = functions.firestore.document('/payments/{paymentId}')
.onWrite((change : Change <DocumentSnapshot>) => {
change.after.ref.get().then((doc: DocumentSnapshot )=> {
const payment : Payment = doc.data();
})
[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?
Do I just use:
const payment : Payment = <Payment>doc.data();
Or is there a much nicer solution?
1 Answer
1
The solution you have is just typecasting the doc.data()
. That is
not a solution, its a workaround. Because, by doing so you might face
run time errors.
doc.data()
So, what I would suggest is, just use :
const payment = doc.data()
const payment = doc.data()
In case of const
, the typing will be automatically enforced.
const
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.