Unable to utilize object functions post-casting操作。

I've encountered an issue while trying to access some methods of my model object as it keeps returning an error stating that the function does not exist.

Below is the model class I have created :

class Expense {
  private name: string;
  private title: string;
  private amount: number;
  private description: string;
  private date: Date;
  private status: string;
  public formatetdDate: string;
  private _id : string;
  constructor(name: string, title: string, amount: number, description: string, date: Date, status: string) {
    this.name = name;
    this.title = title;
    this.amount = amount;
    this.description = description;
    this.date = new Date(0);
    this.status = status;
    this.formatetdDate = this.dateFormat();
  }

  public getDate(): Date {
    return this.date;
  }
  public dateFormat(): string {

    let dd = this.date.getDate();
    let mm = this.date.getMonth() + 1;
    const yyyy = this.date.getFullYear();

    if (dd < 10) {
      dd = +`0${dd}`;
    }
    if (mm < 10) {
      mm = +`0${mm}`;
    }
    console.log(dd + '/' + mm + '/' + yyyy);
    return dd + '/' + mm + '/' + yyyy;
  }
}
export default Expense;

Currently, I am fetching data from the server using http requests and mapping it to this model :

   this.expenseService.getExpensesList().subscribe((expenses) => {
      if (expenses.success) {
        this.expensesList = expenses.data as Expense[];
        this.total = +expenses.total;
        this.pages = +expenses.pages;
        this.limit = +expenses.limit;
      } else {
        alert(expenses.message);
      }
    });

If I attempt to execute the following actions :

this.expensesList[0].getData()

or

this.expensesList[0].dateFormat()

an error is consistently thrown mentioning that these functions do not exist. However, when attempting to print the date with (this.expensesList[0].date), an error occurs due to access violation (private).

Can anyone point out what mistake I might be making?

Thank you

Answer №1

When using 'as Expense[]', you are providing a type hint to Typescript that informs it that expenses.data is an array of Expense objects, even if Typescript may have inferred something different. However, in reality, these are not actual Expense objects; they are just plain objects (or at least that's what it seems like). To turn them into true Expense objects with a getDate method, you must iterate through the data and create new Expense objects from them.

Attempting to print the date (this.expensesList[0].date) will result in an error due to access violation (private).

Indeed, this happens because you have convinced the static type checker that you are trying to access a property of an Expense object, whether that is accurate or not.

Therefore, it is best to use the as operator cautiously and only when you fully understand its implications; improper usage can hinder the type checker's functionality, leading to runtime errors that could have been prevented during compilation.

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

Is there a way to send a personalized reply from an XMLHttpRequest?

My goal is to extract symbol names from a stocks API and compare them with the symbol entered in an HTML input field. I am aiming to receive a simple boolean value indicating whether the symbol was found or not, which I have implemented within the request. ...

Encountering Axios 404 error while trying to access the routes directory

My server.js file in Express and Node.js contains the bulk of my back-end code, except for my database config file. The file is quite lengthy, and I want to enhance maintainability by breaking it down into smaller modules that can be imported. To start t ...

I am looking to implement tab navigation for page switching in my project, which is built with react-redux and react-router

Explore the Material-UI Tabs component here Currently, I am implementing a React application with Redux. My goal is to utilize a panelTab from Material UI in order to navigate between different React pages. Whenever a tab is clicked, <TabPanel value ...

It appears that the Angular 2 HTTP header is being produced or transmitted erroneously

Trying to send a request to my backend that uses HTTP Basic authentication for testing purposes. username: user password: password The correct header should be: Authorization: Basic dXNlcjpwYXNzd29yZA== Request tested with this header in Chrome Advance ...

When attempting to import the OrbitControls.js file, Three.js encounters an error and fails

I am completely new to javascript and unfamiliar with working with libraries. I am currently experimenting with basic three.js code, but unfortunately facing issues that I cannot seem to resolve. Following the documentation on Threejs.org, I have set up a ...

Utilizing the Twitter API variable within ExpressJS while incorporating AngularJS

Using the "twit" Twitter package from GitHub, I am able to call the Twitter API and retrieve data that is logged in the console. However, I am unsure of how to pass this data to AngularJS in order to display the tweets on the front-end. T.get('search ...

A comparison between the if statement and switch statement in JavaScript

Let's dive into a challenging scenario for those who consider themselves experts in JavaScript, particularly with switch and if statements. Here is how it typically works: var a = 1; if (a == 1) alert("true"); This is just a basic example. Now, let& ...

The confusion surrounding navigation in Angular's single-page applications

I'm struggling to grasp how Angular handles routing in my single-page application. Here's my issue: When I type in the url: localhost:3000/streams/ I expect the 'streams' page to load. My understanding was this: My express serve ...

Leveraging the wheelDelta property in the onmousewheel event handler with Script#

When working with Script#, I often utilize mouse events using the ElementEvent argument. However, one thing seems to be missing - the WheelDelta property for handling the onmousewheel event. Can anyone provide guidance on how to access this property in t ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Utilize D3 to Rotate Text within an SVG in Circular Motion, Following by Self-rotation

In my visualization, the labels are arranged around the center of a circle by rotation. However, this results in the labels on the left side of the circle appearing upside down. Is there a way to rotate the labels on the left side independently after the i ...

Utilize JavaScript to parse HTML content retrieved through AJAX requests

My current project involves writing JavaScript code, specifically a Chrome extension, that needs to: Retrieve the contents of a web page using AJAX. Extract specific content from the page by identifying certain elements within the HTML string and retriev ...

What is the best way to keep a header row in place while scrolling?

I am looking to keep the "top" row of the header fixed or stuck during page scrolling, while excluding the middle and bottom rows. I have already created a separate class for the top row in my header code: view image description ...

Interacting with a WebGL globe: accessing database information and displaying pop-up windows when clicking on specific locations on the globe

I am working on creating a WebGL Globe similar to the one found at this link: Currently, I have been using this example as a reference point: Here are the specific project requirements that I am aiming to achieve: The website needs to be able to manage ...

Utilizing external applications within Angular applications

I have the task of creating a user interface for clocker, a CLI-based issue time tracker. Clocker functions as a stand-alone node.js application without any programming interface. To begin tracking time for an issue labeled 123, the command would typically ...

Executing a Jquery click event after a delay with setTimeout

I am working with an <a> element that, when clicked, triggers a handler like this: function onCummReportClick(e) { if ($(e.currentTarget).attr('href').indexOf('csv') !== -1) { { return true; } //Here s ...

Obtaining personalized error messages from the backend with express: A step-by-step guide

I'm currently developing a Login App and I'm looking to implement custom error messaging on the Front End. Specifically, I want to display custom error messages when attempting to register with an email that is already in use or when entering a p ...

Update a value in the sessionStorage using Angular

I am working on a function that handles checkbox options based on event.target.name. The goal is to add the checkbox option to session storage if it's not already there, and update the value if it exists. However, I'm facing some issues with my c ...

When I click the button, it deletes the DOM element and hides it, preventing me from

I'm facing a simple issue that I can't quite wrap my head around. Whenever I input a value into the form and click the button to run the function, the 'loading' element disappears and doesn't reappear. Here is the JavaScript code ...

Dynamically loading Ember templates with asynchronous requests

I need a way to dynamically load HTML content from another file using the code below: App.MainView = Ember.View.extend({ template:function(){ $.ajax({ url: 'views/main.html', dataType: 'text', async: false, ...