Skip to content

Instantly share code, notes, and snippets.

@SpenceDiNicolantonio
Last active April 29, 2024 14:15
Show Gist options
  • Save SpenceDiNicolantonio/e73fd9e4415cc68d427db80fea7598e3 to your computer and use it in GitHub Desktop.
Save SpenceDiNicolantonio/e73fd9e4415cc68d427db80fea7598e3 to your computer and use it in GitHub Desktop.
Typesafe Firestore collection #firebase #firestore #typescript
// 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