我刚刚开始使用打字稿,希望您能为我提供帮助,我不知道如何解决此错误
接口
export interface IProduct {
name: string;
price: number[];
stock: number;
createdAt: firestore.Timestamp
}
export interface IDataProduct {
[key: string]: IProduct
}
从Firestore获取产品列表
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}
}
我无法解决
答案 0 :(得分:0)
如果您要假设x.data()
返回一个完全符合IProduct
接口的对象,则必须将其强制转换:
products[x.id] = x.data() as IProduct