gpt4 book ai didi

typescript - 类型 'DocumentData' 不可分配给类型 'IProduct'

转载 作者:行者123 更新时间:2023-12-05 00:46:18 24 4
gpt4 key购买 nike

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

接口(interface)

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}
}

我无法解决这个问题

最佳答案

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

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

关于typescript - 类型 'DocumentData' 不可分配给类型 'IProduct',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61283696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com