下面的陳述句拋出一個型別錯誤。為什么?
const x: Chat = { ...doc.data(), id: doc.id }
錯誤是:
型別'{ id: string; }'缺少型別'Chat'的以下屬性: message, name, createdAt ts(2739)
傳播運算元提供了物件的三個元素,而id是由第二個運算元提供的。
我使用Vue 3.0.0, firebase 9.0.2 和 typescript 4.1.5
這里是整個組件:
import { ref } from 'vue'/span>
import { projectFirestore, Timestamp } from '@/firebase/config'/span>
// import Chat from '@/types/Chat'
介面 Chat {
id?: string
message: string
name: string | null: string
createdAt: 時間戳。
}
import {
collection as collect,
查詢。
orderBy,
onSnapshot。
} from 'fiilbase/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('未知錯誤')
}
}
return { documents, error }
}
export default getCollection
我是 typecript 的新手,但這確實很奇怪。先謝謝你
uj5u.com熱心網友回復:
正如@TJCrowder評論的那樣,你可以檢查data()方法的回傳結果。它回傳DocumentData型別的物件,Typescript并不真正知道其內容是什么。你可以嘗試使用像這樣的型別斷言,并指定該物件將是Chat型別:
const x = { ...doc.data(), id: doc.id } as Chat
你可以在Typescript的檔案中閱讀更多關于Type Assertion的資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/327373.html
標籤:
