类型“DocumentData”不可分配给类型“IProduct”

And*_*bor 5 firebase typescript google-cloud-firestore

我刚刚开始使用打字稿,我希望你能帮助我,我不知道如何解决这个错误

\n\n

接口

\n\n
export interface IProduct {\n  name: string;\n  price: number[];\n    stock: number;\n    createdAt: firestore.Timestamp\n}\n\nexport interface IDataProduct {\n    [key: string]: IProduct\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

从 firestore 获取 ProductList

\n\n
export const fetchProducts = () => \n    async (dispatch: Dispatch, getState: () => any, { db }: IServices) => {        \n        try {\n            const snaps = await db.collection(\'productos\').get()\n\n            let products: IDataProduct = {}\n            snaps.forEach(x => {\n             return products[x.id] = x.data()\n            })\n\n            dispatch(fetchSucess(products))\n    } catch (error) { dispatch(fetchError(error)) }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

错误\n 类型\'DocumentData\'无法分配给类型\'IProduct\'。\n类型\'DocumentData\'缺少类型\'IProduct\'中的以下属性:name、precio、stock、createdAt \在这里return products[x.id] = x.data()

\n\n

x返回

\n\n
{\nid: "IgzlwT6OlazrlBTmAIj4"\nref: (...)\nexists: (...)\nmetadata: t\nim: t {xT: FirebaseAppImpl, BT: t, INTERNAL: {\xe2\x80\xa6}, OT: t, WT: "[DEFAULT]", \xe2\x80\xa6}\nem: t {path: n}\nlm: n {key: t, version: t, Ee: t, te: false, hasCommittedMutations: false}\ndm: false\nfm: false\nom: undefined\n__proto__: t\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

x.data()返回

\n\n
{\nstock: 64\nname: "ProductName 50Kg"\nprice: (3) [24, 23, 20]\ncreatedAt: t {seconds: 1587099600, nanoseconds: 0}\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我无法解决这个问题

\n

Dou*_*son 14

如果您想假设x.data()返回一个完全符合接口的对象IProduct,则必须对其进行强制转换:

products[x.id] = x.data() as IProduct
Run Code Online (Sandbox Code Playgroud)