Defining TypeScript interface types for documents of a Snapshots
See original GitHub issueWouldn’t it be somehow possible to define the types of the documents which are returned by snapshot.data()
and snapshot.get()
even better with TypeScript?
Currently, when calling these methods on a snapshot, the type is unknown… I think this could be even better if we as developers could define and describe the documents which are fetched into snapshots. I think that maybe one could use generics where an interface type is put in like this:
const userSnap: FirebaseFirestore.DocumentSnapshot<UserDoc> = await firestore.collection("users").doc(uid).get();
const languageRef: FirebaseFirestore.DocumentReference = userSnap.get("language");
Here I define in a generic the type that the object should have when I call snapshot.data()
:
const userSnap: FirebaseFirestore.DocumentSnapshot<UserDoc>
I define a type UserDoc
which I can then define as a generic of DocumentSnapshot
and with this definition the call to .data()
returns an object with the correct type of UserDoc
AND
even better would be if even the call to snapshot.get()
would return the correct type here:
const languageRef: FirebaseFirestore.DocumentReference = userSnap.get("language");
So that I don’t explicitly have to define the type of languageRef
and TypeScript knows exactly that the type should be of FirebaseFirestore.DocumentReference
, without any further type definition.
So this code:
const userSnap: FirebaseFirestore.DocumentSnapshot = await firestore.collection("users").doc(uid).get();
const languageRef: FirebaseFirestore.DocumentReference = userSnap.get("language");
becomes this:
const userSnap: FirebaseFirestore.DocumentSnapshot<UserDoc> = await firestore.collection("users").doc(uid).get();
const languageRef = userSnap.get("language");
In my opinion a lot more readable and with a good typescript compatilbe editor at least as good as defining the type manually each time you call .get()
or .data()
I love to hear what you think, if this is possible or something as useful for others as it would be for me.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:14
- Comments:6 (2 by maintainers)
@creativecreatorormaybenot Yes, this is implemented (as shown by your code snippets).
@IchordeDionysos That is pretty sweet, thanks 😋
For reference:
Or for interfaces (akin to my previous comment):