I am using firebase-admin
to control a firestore database using Cloud Functions with TypeScript. If I set the type of my collection reference, I can no longer add
using FieldValue
s. The argument types from add
require a literal object matching the collection document, without any FieldValue
s. What is a supported pattern for using FieldValue
s with firebase-admin
in TypeScript? Any answer using the base libraries with FieldValue
s will do.
Here is a minimal example with FieldValue.serverTimestamp
:
import { firestore, initializeApp } from 'firebase-admin'
import { firebaseConfig } from './secret'
import { https } from 'firebase-functions'
interface User {
id?: string
displayName: string
createdAt: firestore.Timestamp
}
const converter = {
toFirestore: (data: User) => data,
fromFirestore: (snapshot: firestore.QueryDocumentSnapshot<User>): User => {
const data = snapshot.data()
const doc = { id: snapshot.id, ...data }
return doc
}
}
initializeApp(firebaseConfig)
const db = firestore()
const usersCollectionRef = db.collection('users').withConverter(converter)
export const cloudFunction = https.onCall(async (props, context) => {
const newUserData = {
displayName: 'New User',
createdAt: firestore.FieldValue.serverTimestamp()
}
await usersCollectionRef.add(newUserData)
// Argument of type '{ displayName: string; createdAt: firestore.FieldValue; }' is not assignable to parameter of type 'User'.
// Types of property 'createdAt' are incompatible.
// Type 'FieldValue' is missing the following properties from type 'Timestamp': seconds, nanoseconds, toDate, toMillis
})
Similarly, with FieldValue.arrayUnion
:
interface User {
id?: string
friendNames: string[]
}
const converter = {
toFirestore: (data: User) => data,
fromFirestore: (snapshot: firestore.QueryDocumentSnapshot<User>): User => {
const data = snapshot.data()
const doc = { id: snapshot.id, ...data }
return doc
}
}
initializeApp(firebaseConfig)
const db = firestore()
const usersCollectionRef = db.collection('users').withConverter(converter)
export const cloudFunction = https.onCall(async (props, context) => {
await usersCollectionRef.add({
friendNames: firestore.FieldValue.arrayUnion('BFF')
// Type 'FieldValue' is missing the following properties from type 'string[]': length, pop, push, concat, and 29 more.
})
})
2
Answers
I think you need to define
createdAt
asTimestamp
TypeI believe this should fix the problem
Try this
then use it like this: