Attempting to type the err
object in a function that saves documents to Firestore has been challenging.
async function saveToFirestore(obj: SOME_OBJECT, collection: string, docId: string) {
try {
await firebase.firestore().collection(collection).doc(docId).set(obj);
}
catch(err: firebase.firestore.FirestoreError) {
// THIS DOESN'T SEEM TO BE POSSIBLE
}
}
I also experimented with firebase.FirebaseError
The error I encounter looks like this:
https://i.sstatic.net/EDAWL.png
I'm wondering how to achieve autocomplete for the error object from Firebase. Should the error
object always be typed as any
or unknown
? What is the preferred approach?
UPDATE
Since directly typing the catch(err)
seems impossible, I was aiming for something like this:
catch(err) {
if (err instanceof firebase.FirebaseError) { // <--- THIS DOES NOT WORK
throw `something for the FirebaseError`
}
else {
throw `something else for other error types`
}
}
However, according to the discussion on the issue shared by Frank in his answer, it appears that this approach is not feasible.
_We don't allow type annotations on catch clauses because there's really no way to know what type an exception will have. You can throw objects of any type and system generated exceptions (such as out of memory exception) can technically happen at any time. Even if we had a Java-like notion of throws annotations it is not clear that we could ever really rely on them. (And, it is also not clear that they work all that well in Java, but that's another discussion.)_
We don't narrow any in type guards unless we know the exact type you're narrowing to. For example, if you check typeof x === "string" we will indeed narrow an any to string because we know for sure that is the exact type of x. That isn't the case with instanceof. Specifically, you might check x instanceof Base, but x might actually be an instance of a class derived from Base. If we narrowed x to type Base you'd see errors on access to properties of the derived class even though there is nothing wrong with the code. Now, before you argue those errors would be fine, keep in mind that the declared type of x is any, so you've already said you want no checking. We take that as an indication that we should issue errors only when we're 100% sure they're errors. And we only know that if we know the exact type.