【问题标题】:Type 'DocumentData' is not assignable to type 'IProduct'类型“DocumentData”不可分配给类型“IProduct”
【发布时间】:2020-04-18 02:55:05
【问题描述】:

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

接口

export interface IProduct {
  name: string;
  price: number[];
    stock: number;
    createdAt: firestore.Timestamp
}

export interface IDataProduct {
    [key: string]: IProduct
}

从 Firestore 中获取 ProductList

export const fetchProducts = () => 
    async (dispatch: Dispatch, getState: () => any, { db }: IServices) => {        
        try {
            const snaps = await db.collection('productos').get()

            let products: IDataProduct = {}
            snaps.forEach(x => {
             return products[x.id] = x.data()
            })

            dispatch(fetchSucess(products))
    } catch (error) { dispatch(fetchError(error)) }
}

错误 " 类型“DocumentData”不可分配给类型“IProduct”。 “DocumentData”类型缺少“IProduct”类型的以下属性:名称、价格、库存、createdAt " 在这里return products[x.id] = x.data()

x 返回

{
id: "IgzlwT6OlazrlBTmAIj4"
ref: (...)
exists: (...)
metadata: t
im: t {xT: FirebaseAppImpl, BT: t, INTERNAL: {…}, OT: t, WT: "[DEFAULT]", …}
em: t {path: n}
lm: n {key: t, version: t, Ee: t, te: false, hasCommittedMutations: false}
dm: false
fm: false
om: undefined
__proto__: t
}

x.data() 返回

{
stock: 64
name: "ProductName 50Kg"
price: (3) [24, 23, 20]
createdAt: t {seconds: 1587099600, nanoseconds: 0}
}

我无法解决这个问题

【问题讨论】:

    标签: typescript firebase google-cloud-firestore


    【解决方案1】:

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

    products[x.id] = x.data() as IProduct
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-19
      • 2022-01-27
      • 2021-10-26
      • 2020-04-02
      • 2019-06-02
      • 2018-01-04
      • 2020-11-09
      • 1970-01-01
      相关资源
      最近更新 更多