Andres Gaibor
Andres Gaibor

Reputation: 153

Type 'DocumentData' is not assignable to type 'IProduct'

I am just starting to use typescript, I hope you can help me, I don't know how to solve this error

Interfaces

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

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

Get ProductList from the 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)) }
}

The error " Type 'DocumentData' is not assignable to type 'IProduct'. Type 'DocumentData' is missing the following properties from type 'IProduct': name, precio, stock, createdAt " is here return products[x.id] = x.data()

x return

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

and x.data() return

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

I can't resolve this

Upvotes: 5

Views: 3948

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317497

If you want to make the assumption that x.data() returns an object that fully conforms to the IProduct interface, you will have to cast it:

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

Upvotes: 15

Related Questions