Dealing with Typescript Errors in Ionic3: How to Handle "Property 'x' does not exist on value of type 'y'" Issues

I stumbled upon this particular post (and also this one) while searching for a solution to my issue.

I am looking to suppress these specific errors:

'Payload' property is missing from the 'Matatu' type.

'Key' property is not found on type 'Matatu'.

I have attempted to define variables to go around the type system, but without success.

Below you can find my .ts code and what I have tried so far:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ActionSheetController } from 'ionic-angular';
import { AngularFireList, AngularFireDatabase } from 'angularfire2/database';
import { Matatu } from '../../models/matatu/matatu.interface';
/* imports */

declare var payload;
declare var key;

@IonicPage()
@Component({
  selector: 'page-owner-dash',
  templateUrl: 'owner-dash.html',
})
export class OwnerDashPage {

  matatuListRef$: AngularFireList<Matatu>;
  matatuListAsync$: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, private database: AngularFireDatabase, public actionShtCrtl: ActionSheetController) {

    this.matatuListRef$ = this.database.list('matatu-list');
    this.matatuListAsync$ = this.matatuListRef$.snapshotChanges();

  }

  ionViewDidLoad() {
   //things 
  }

  selectMatatu(matatu: Matatu){
    this.actionShtCrtl.create({
      title: `${matatu.payload.val().matNumberPlate}`,
      buttons: [
        {
          text: 'Edit',
          handler: () => {
            //actions
          }          
        },
        {
          text: 'Delete',
          role: 'destructive',
          handler: () => {
            this.matatuListRef$.remove(matatu.key);
          }
        },
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            //perform some actions
          }
        }
      ]
    }).present();
  }


}

Below is the structure of Matatu:

export interface Matatu {
    $key?: string;
    matNumberPlate: string;
    matSacco: string;
    matDriver: string;
    matAccessCode: string;
    matStatus: string;
    matTracker: string;
    matLocation: string;

}

How can I convert the property to any data type?

Answer №1

How can I convert the property to any data type?

If your goal is simply to convert it in order to prevent a TypeScript error, you could try the following approach:

// ...
title: `${(<any>matatu).payload.val().matNumberPlate}`,
// ...

Additionally,

// ...
this.matatuListRef$.remove((<any>matatu).key);
// ...

By doing this, the variable matatu will be converted to type any, resolving the error.


In my opinion, if you are able to modify the Matatu interface, it would be beneficial to include these two properties within it:

export interface Matatu {
    $key?: string;
    matNumberPlate: string;
    matSacco: string;
    matDriver: string;
    matAccessCode: string;
    matStatus: string;
    matTracker: string;
    matLocation: string;

    // The new properties are optional
    payload?: any;
    key?: any;
}

This way, there would be no need to convert the matatu property since both payload and key are defined in the Matatu type (and both have a type of any).

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

Angular, Transforming JSON with RxJS Operators in TypeScript

Upon receiving the JSON object (Survey) from the server, it looked like this: { "id": 870, "title": "test survey", "questions": [ { "id": 871, "data": ...

Implementing dynamic background images in Angular 4 using div placeholders

Is there a way to include a placeholder or default image while waiting for item.imgSrc to load on the screen? <div class="style" *ngFor="let item of array; <div [style.backgroundImage]="url('+ item.imgSrc +')" class="image">< ...

When you click, you will be directed to the specific details of the object

I have a recipe component that displays a list of recipes from my database and a recipe-detail component that should show the details of a selected recipe. What I aim to achieve is that when someone clicks on a recipe name, they are routed to the recipe-de ...

How can Angular 2 populate forms with data retrieved from a promise in a database?

I'm currently navigating through the world of Angular and Firebase, and I’ve hit a roadblock when it comes to populating my forms with data from Firebase promises. Understanding how to work with promises versus observables is also proving to be a ch ...

When using Jest + Enzyme to test a stateful class component, encountering problems with Material-UI's withStyles functionality is a common issue

I have a React + TypeScript application with server-side rendering (SSR). I am using Material-UI and following the SSR instructions provided here. Most of my components are stateful, and I test them using Jest + Enzyme. Below is an example of one such com ...

How can I adjust the width of a td table in an Angular 6 component template using Bootstrap?

I am currently working on a project using Angular 6. Here is a snapshot of the screen I am working on: https://i.stack.imgur.com/hQLOI.png The screen consists of two main elements - an HTML table and a component that represents the table data in individ ...

`Running ng serve will result in the creation of a 'dist' folder within each app sub

Since beginning my project, I have encountered an issue that is both normal and frustrating. The dist folder is being created with incomplete information related to the components inside it. dashboard dist (unwanted) components panel dist (unwanted) c ...

The specified path is not found within the JsonFilter

Something seems off. I'm using Prisma with a MongoDB connection and attempting to search the JSON tree for specific values that match the [key, value] from the loop. However, I haven't made much progress due to an error with the path property. Be ...

Transforming the string attribute of an object within a JavaScript array through mapping

Here is an array of objects: { "attr1": 123, "attr2": "a.end", }, { "attr1": 123, "attr2": "b.start", } The task is to remove the first part of the attr2 string up to and including the '.& ...

Dealing with errors from APIs in a React TypeScript application

Currently, I am in the process of learning React and Typescript by creating a demo application. This app sends a request to the API located at in order to retrieve postcode information and display details about a specific location based on the entered pos ...

Learn how to leverage Angular 4's ngComponentOutlet to dynamically pass values from an array

Check out this Plunker demo: https://plnkr.co/edit/JvXBLOVaeaYO5bmMQa6a?p=preview In the Plunker example, I have created 3 boxes using an ngFor loop from an array. Each box has its own event listener attached to it. The goal is to generate a component whe ...

Combining SignalR and Angular: Steps for incorporating a Bearer token into Http Headers

Recently, I developed an asp.net core 2.0 SignalR Hub that utilizes a Bearer Token for Authentication. However, I am encountering some confusion when trying to establish a connection with the SignalR Angular 5 client. Interestingly, the connection succeeds ...

Styling Dynamic HTML Content in Angular: Tips and Tricks

After running this line of code, I have a generated element sub with a property of [sub]. <li [displayMode]="displayMode" template-menu-item style="cursor: pointer" [routerLink]="['/request/checkoutReview']" icon="fa-shopping-cart" name ...

What is the best way to handle asynchronous actions while initializing a database in Next.js?

My goal is to create tables during the database initialization stage with a structure like this: CREATE TABLE IF NOT EXISTS users ( "id" SERIAL PRIMARY KEY, "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "name&quo ...

The inclusion of Angular 2 router queryParams in the URL is not happening

I implemented an auth guard to protect certain pages of my web-app. In order to enable users to return to the page they intended to access, I tried adding queryParams to the URL during a redirect. Initially, the code below worked as expected. However, rece ...

Tips for using Angular's formatDate function to format dates

I am attempting to achieve a specific format using Angular's formatDate "2019-01-01T00:00:00Z" Here is the code I am using: formatDate( '2019-01-01', 'yyyy-MM-ddT00:00:00Z', 'en-US' ) The output I am getting is ...

Peer dependencies in NPM refer to dependencies that your project

I am currently in the process of upgrading from Angular 4 to Angular 5 and encountered some warnings along the way. Some of the warnings I received include: npm WARN @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88eb ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...

Having trouble installing Popper.js?

I have encountered an issue while attempting to install popper.js in my angular project. ng new <<project>> cd <<project>> npm install popper --save npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules&b ...

Encountering difficulty in removing a record from the database utilizing Prisma with Next.js API routes

Currently, I am in the process of developing a Todo manager using Next.js 13, Prisma, and MySQL. In order to include a feature that allows users to delete a todo item, I have implemented the use of a Link tag for the delete button within my code: ... <L ...