Can you explain why the following statement is throwing a type error?
const x: Chat = { ...doc.data(), id: doc.id }
The error message states:
Type '{ id: string; }' is missing the following properties from type 'Chat': message, name, createdAt ts(2739)
This code snippet uses the spread operator to extract three elements of an object, leaving id provided by the second operand.
The technologies being used are Vue 3.0.0, firebase 9.0.2, and typescript 4.1.5
Below is the complete component for reference:
import { ref } from 'vue'
import { projectFirestore, Timestamp } from '@/firebase/config'
interface Chat {
id?: string
message: string
name: string | null
createdAt: Timestamp
}
import {
collection as collect,
query,
orderBy,
onSnapshot,
} from 'firebase/firestore'
const getCollection = (collection: string) => {
const documents = ref<Chat[]>()
const error = ref<string>()
try {
const q = query(
collect(projectFirestore, collection),
orderBy('createdAt', 'desc')
)
const unsubscripe = onSnapshot(q, (querySnapshot) => {
const results: Chat[] = []
querySnapshot.forEach((doc) => {
const x: Chat = { ...doc.data(), id: doc.id }
doc.data().createdAT && results.push(x)
})
documents.value = results
})
} catch (err) {
if (err instanceof Error) {
error.value = err.message
} else {
throw Error('Unknown Error')
}
}
return { documents, error }
}
export default getCollection
I'm still learning TypeScript, so any insights would be greatly appreciated. Thank you!