Last active
April 29, 2024 14:15
-
-
Save SpenceDiNicolantonio/e73fd9e4415cc68d427db80fea7598e3 to your computer and use it in GitHub Desktop.
Typesafe Firestore collection #firebase #firestore #typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A generic Firestore converter that provides type inference | |
export const genericConverter = <T>() => ({ | |
toFirestore: (data: PartialWithFieldValue<T>) => data ?? {}, | |
fromFirestore: (snap: QueryDocumentSnapshot) => snap.data() as T, | |
}); | |
// A wrapper of collection() that uses a generic converter to provide type inference | |
export const typedCollection = <T>(db: Firestore, name: string) => | |
collection(db, name).withConverter<T>(genericConverter<T>()); | |
// Example usage: | |
type User = { name: string; age: number }; | |
onSnapshot(typedCollection<User>(db, 'users'), (snapshot) => { | |
requests = snapshot.docs | |
.map((doc) => doc.data()) | |
.map((doc) => ({ | |
text: doc.name, | |
upvotes: doc.age, | |
})); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment