I've been working on a Vue composable using TypeScript that utilizes a generic type T
and accepts a single parameter path
, ultimately returning a reference to a document
.
While I have made progress, I keep encountering an error when trying to set a value to the document
ref:
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)
Below is a condensed version of the composable code:
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;
Despite experimenting with various assignments to document.value
such as strings or {} objects, I continue to receive similar errors indicating incompatibility with type T
.
I recognize that the issue lies in TypeScript's uncertainty regarding type T
's compatibility with other types. Is there a way to inform TypeScript that type T
can indeed work with these various types?