Error message: The property 'data' is not recognized within this context. Additionally, the property 'datatime' does not exist on the current type

I'm currently working on generating a graph using Firestore data and ng2charts. However, when I run my code, I encounter the following errors:

Property 'data' does not exist on type 'unknown', causing an error in item.data

Similarly, property 'datatime' does not exist on type 'unknown', leading to an error in item.datatime

How can I resolve these issues?

Here is the component code I am using:


  labelsdatatimeArray: any = [];
  dataArray: any = [];

  @ViewChild(BaseChartDirective) chart: BaseChartDirective | undefined;

  constructor(public navCtrl: NavController, private firestore: AngularFirestore) { }

    ngOnInit() {
      this.firestore.collection('/ELGeneraciónEmpleosFormalesDiciembreCadaAño/').get().toPromise().then((snapshot) => {
      snapshot.docs.forEach(doc => {
      let item = doc.data();

      let data = item.data;
      this.dataArray.push(data);

      let datatime = item.datatime;
      this.labelsdatatimeArray.push(datatime);
    });
  });

  }
  
  public barChartOptions: ChartConfiguration['options'] = {
    responsive: true,

    scales: {
      x: { ticks: {
        stepSize: 1,
        maxRotation: 60,
        minRotation: 60,
        autoSkip: false
     }},
      y: {
        min: -40
      }
    },
    plugins: {
      legend: {
        display: true,
      },
      datalabels: {
        anchor: 'end',
        align: 'end'
      }
    }
  };
  public barChartType: ChartType = 'bar';
  public barChartPlugins = [
    DataLabelsPlugin
  ];

  public barChartData: ChartData<'bar'> = {
    labels: [this.labelsdatatimeArray],
    datasets: [ 
      { data: [this.dataArray],
        label: '' },
    ]
  };

  // events
  public chartClicked({ event, active }: { event?: ChartEvent, active?: {}[] }): void {
    console.log(event, active);
  }

  public chartHovered({ event, active }: { event?: ChartEvent, active?: {}[] }): void {
    console.log(event, active);
  }

Answer №1

If the item is considered an unknown value, it is advisable to incorporate type-checks rather than resorting to using any in order to prevent compilation errors.

You have the option to utilize the following type guards:

let item = doc.data(); // assuming item is unknown

// Considering that I am unaware of the specific data type in your scenario
// you can define a precise type that you expect instead of utilizing any
let data =
  item && typeof item === "object" && "data" in item
    ? (item! as { data: any /** Use specific type here */ }).data
    : null; 

if(!data){
    // handle null data
    // Nonetheless, if you are certain that there will be a value in data, this if statement can be omitted
}

// Similar approach for datetime
let datetime =
  item && typeof item === "object" && "datetime" in item
    ? (item! as { datetime: any }).datetime
    : null;

if(!datetime){
    // handle null datetime
    // However, if you are confident of receiving a value in datetime, the if check can be excluded
}

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

Having trouble with my Angular 4 application when trying to make a POST request to a

I am struggling to create a straightforward login verification process using Angular 4, PHP, and MySQL. Currently, I can successfully send the user details to PHP but I am unable to retrieve the status afterward, and I'm not sure why. Basically, I ne ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

Connect the Result of a Button Click to a Fresh Span

Just starting out with Angular2 so I'm keeping things simple for now. I understand the importance of separating feature components, but my main focus at the moment is getting everything to function properly. My objective here is to bind the value of ...

Is it necessary for the version of the @types packages in TypeScript to match their non-types packages?

Are @types and untyped packages versioned the same way? npm i bluebird @types/bluebird -S returns "@types/bluebird": "^3.5.0", "bluebird": "^3.5.0", This seems logical. npm i request @types/request -S yields "@types/request": "0.0.41", "request": "^2. ...

Version 4 of Typescript is experiencing crashes when spreading optional arguments

Previously with TypeScript 3.9+, this setup was functioning perfectly: type keys = | 'one' | 'another' | 'yet_another'; type variables = { 'another': { count: number } 'yet_another': { ...

Guide to including spinner in React JS with TypeScript

I need help with adding a spinner to a React component. The issue I'm facing is that the spinner does not disappear after fetching data from an API. Can someone please point out what I am doing wrong? Here is the code snippet: import React, { useSta ...

Ensure that the interface limits the key value to match precisely the value of a constant in Typescript

Seeking assistance in understanding how to enforce a specific type for an optional key within an interface: const FIRST = "FIRST" const SECOND = "SECOND" interface TSomeInterface { element: Element order?: typeof FIRST | typeof ...

There seems to be a troublesome character in the Nuxt3 production server causing some issues

When submitting an HTML encoded text to the server, everything runs smoothly on the development environment. However, once it is deployed to a Netlify server, the same request triggers a 500 error and the server side logging middleware only recognizes a PO ...

What changes occur to the files in an Angular project, specifically Angular 8, when the npm install command is run?

When running "npm install" in an Angular project (specifically angular 8), which files are created or modified? Do I need to delete the package.lock.json file along with the node_modules folder when updating something in the package.json file? Will npm i ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

What is the best way to retrieve the data from a specific section when a checkbox is selected in Angular 2?

When I select a checkbox for any section and then click the submit button, I want to display the details of that section in the console. Can someone assist me with this? **Stackblitz link:** : https://stackblitz.com/edit/angular-q7y8k1?file=src%2Fapp%2Fa ...

Is it possible to utilize types as constants in a switch statement?

In my file called checkoutTypes.ts, I have defined some checkout types like this: export type CheckoutInvoiceAddressSection = "InvoiceAddress"; export type CheckoutDeliveryAddressSection = "DeliveryAddress"; export type CheckoutDelivery ...

Angular data binding with [object object]

Upon receiving data from my API, the console displays the following structure: [ { id:"123", name:"asd", address:"st.dddss", status:1 } ] After attempting to iterate through it using ngFor, an error is thrown: E ...

What is the process for implementing angular-material's pre-defined theme variables in component styling?

I was trying to create a more dynamic background-color for my .active class within my mat-list-item Here is the HTML: <mat-list-item *ngFor="let page of pages" matRipple routerLinkActive="active" > < ...

When adding new elements to an array, the IDs of all objects become identical

When running the code below: dietDay.meals.forEach((meal) => { meal.mealProducts.forEach((mealProduct) => { if ( mealProduct.product.id && this.fetchedProductIds.includes(mealProduct.p ...

Is there a way to adjust the starting and ending points of a bezier curve in D3 by utilizing the link generator?

I'm currently working on developing a horizontal hierarchical tree Power BI custom visual using TypeScript and D3. I am utilizing d3's treeLayout for this purpose, and my task is to create a link generator that can plot bezier, step, and diagonal ...

Customizing modal window HTML in ng-bootstrapNeed to override the default modal window

Currently, I am utilizing ng-bootstrap to create my modals. I have been pondering the most effective approach to customize the modal window's HTML. The default appearance of the modal html is somewhat like this: <div role="document" class="modal- ...

What is the method for implementing type notation with `React.useState`?

Currently working with React 16.8.3 and hooks, I am trying to implement React.useState type Mode = 'confirm' | 'deny' type Option = Number | null const [mode, setMode] = React.useState('confirm') const [option, setOption] ...

What is the proper way to utilize the router next function for optimal performance

I want to keep it on the same line, but it keeps giving me errors. Is there a way to prevent it from breaking onto a new line? const router = useRouter(); const { replace } = useRouter(); view image here ...

Developing a search feature using Angular 6 with Observable subscription for the FrontEnd application

I have a unique challenge where I need to implement a full text search in the FrontEnd due to restrictions with the API. When the frontend starts up, it fetches all data entries from the Backend and subscribes them inside a component using an async pipe. T ...