I am writing a Vue composable using TypeScript.
It takes in a generic type T and a single paramter path, and returns a document ref.
I've almost got it working but whenever I try to assign a value to the document ref it throws an error like this:
Type '{ id: string; }' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to '{ id: string; }'.ts(2322)
Here is a trimmed down version of the composable:
import { ref, Ref } from "vue";
import { projectFirestore } from "@/firebase/config";
import { doc, onSnapshot } from "firebase/firestore";
const getDocument = <T>(
path: string
): {
document: Ref<T | null>;
} => {
const document = ref(null) as Ref<T | null>;
const docRef = doc(projectFirestore, path);
onSnapshot(docRef, (doc) => {
document.value = { //<-- Error here on "document.value"
...doc.data(),
id: doc.id,
};
});
return { document };
};
export default getDocument;
It doesn't matter what I assign to document.value (strings, an empty object, etc) it always gives a similar error saying it is not assignable to type T.
I understand the error is telling me the type T could be anything, and therefore it's not safe to assign these things because the type of the things might be not be compatible with type T.
But how do I solve this problem? Can I somehow tell TypeScript that type T is compatible with other types?
