The data type 'DocumentData' cannot be assigned to type 'IProduct'

I am new to using TypeScript and I could really use some help. I'm stuck on how to fix this error.

Interfaces

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

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

Retrieve ProductList from 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(fetchSuccess(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 found here return products[x.id] = x.data()

x object

{
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() returns

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

I'm having trouble resolving this issue

Answer №1

When operating under the assumption that x.data() will deliver an object adhering entirely to the guidelines of the IProduct interface, you must execute a cast:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform leaflet marker plugin into Typescript format

I recently discovered a leaflet extension that conceals map markers if they fall outside the boundaries of the current view map. import L from 'leaflet'; L.Marker.MyMarker= L.Marker.extend({}).addInitHook(function (this: ILazyMarker) { this ...

Using `publishReplay()` and `refCount()` in Angular does not behave as anticipated when dealing with subscriptions across multiple components

I am currently investigating the functionality of publishReplay in rxjs. I have encountered an example where it behaves as expected: const source = new Subject() const sourceWrapper = source.pipe( publishReplay(1), refCount() ) const subscribeTest1 = ...

The TypeScript Mongoose function is not available for type <Context = any>

How can I implement a schema method in Mongoose and TypeScript to compare passwords? interface IUser extends Document { email: string; username: string; password: string; role: string; comparePassword( candidatePassword: string, next: Nex ...

Retrieve a single document from Firestore and assign it to a variable

While I'm still new to NodeJS, I'm currently working on retrieving a single User document from Firestore. const fs = firebase.firestore(); const usersRef = fs.collection('users'); let findUserByContact = (contact) => { let res ...

What is the best method in typescript to combine objects in an array with identical properties but varying values?

interface IData{ cabinTo:string[]; cabinFrom:string; } const dataAfterIteration= [{cabinTo:"A",cabinFrom:"B"}, {cabinTo:"A",cabinFrom:"C"}, {cabinTo:"B",cabinFrom:"C"}, { ...

Ways to access reference data within the parent data map in Firebase

I'm having trouble making this code work properly. The issue I'm encountering is that the res.data() does not appear in the docs object. getProjects = async () => { const colRef = db.collection('parentCollection').orderBy('c ...

What is the process for defining a recursive array data structure?

Looking to implement a TypeScript method that can navigate through nested arrays of strings when given an instance of a type/class/interface. The method, in concept, should resemble: method<T>(instance: T, arrayAttr: someType) { let tmp = undefin ...

A guide on leveraging *ngFor in Angular 4 to assemble a table featuring 2 columns in every row

I have an array of objects as shown below let columns = [ {id: 1, columnName: 'Column 1'}, {id: 2, columnName: 'Column 2'}, {id: 3, columnName: 'Column 3'}, {id: 4, columnName: 'Column 4'} ]; My ...

No errors are being displayed with the React Hook Form using Zod and Material UI

Presenting my custom ProductInfoForm built using Material UI, react-hook-form with zod validations. However, I am encountering an issue: upon submitting the form, the data is displayed in the console as expected, but when intentionally triggering an error, ...

Troubleshooting the error of an undefined RouterModule

Working on implementing lazy loading for my Angular 4 application, I have a total of 18 lazy loaded modules. Upon noticing that fetching these modules is taking some time, I decided to add a loading indicator. Everything worked fine when I added it locally ...

Guide to automatically closing the calendar once a date has been chosen using owl-date-time

Utilizing Angular Date Time Picker to invoke owl-date-time has been functioning flawlessly. However, one issue I have encountered is that the calendar does not automatically close after selecting a date. Instead, I am required to click outside of the cal ...

Getting the current page name within the app.component.ts file in Ionic 3 - a simple guide

Is it possible to retrieve the current active page name within the app.component.ts file in Ionic without having to add code to any other pages? ...

What is the best way to remove linear-gradient effects applied by a dark mode theme?

Why does MUI add random gradients to components, like in dark mode? Is there a way to disable this feature because it doesn't match the exact color I expected for my custom theme... My Theme Options export const themeOptions: ThemeOptions = { palette ...

What causes TS2322 to only appear in specific situations for me?

I have been trying to create HTML documentation for my TypeScript project using Typedoc. Within one of the many files, there is a snippet of code: public doSomething(val: number | undefined | null | string): string | undefined | null { if (val === null ...

Firebase is not updating the number

Having just started with Firebase, I have been following all the guidelines for web Firebase auth. I have successfully managed to login, log out, and update all data except for the phone number. Despite receiving a success message in the console, my phone ...

Guide to incorporating third-party libraries in Angular

Greetings, I have a common question regarding Angular and utilizing third-party libraries. As someone who does not frequently work with Typescript/Frontends, I am encountering an issue with Angular. Specifically, I am attempting to incorporate the node-htm ...

Guide on specifying a type for a default export in a Node.js module

export const exampleFunc: Function = (): boolean => true; In the code snippet above, exampleFunc is of type Function. If I wish to define a default export as shown below, how can I specify it as a Function? export default (): boolean => true; ...

When merging multiple prop definitions using Object.assign in defineProps, Vue props can be made optional

I have defined a const called MODAL_OPTION_PROP to set common props for a modal: export const MODAL_OPTION_PROP = { modalOption: { type: Object as PropType<ModalOptionParams>, default: DEFAULT_MODAL_OPTION, }, }; I am trying to use it in ...

Tips for ensuring a method is not invoked more than once with identical arguments

I'm grappling with a challenge in JavaScript (or typescript) - ensuring that developers cannot call a method multiple times with the same argument. For instance: const foo = (name: string) => {} foo("ABC") // ok foo ("123") ...

Angular definitely typed does not convert into JavaScript

After installing TypeScript on my VS2013, I obtained the Angular 1.5 Definitely Typed from the NuGet package manager. Although angular.d.ts and its components do not generate angular.js file, when I create another TypeScript file like file1.ts, the file1. ...