The function of getTime is not available for use

I assigned the date_work property to a Date data type. However, when I check the data type using the command

console.log(typeof master.date_work)
, it shows as a string for some reason. This causes an error when using the getTime() function. How can I convert the string data type to a Date?

TypeError: master.date_work.getTime is not a function

Model:

export interface Masters {
    master_id?: string,
    full_name: string,
    comment: string,
    date_work: Date,
    teams_id: string
}

ts:

reports: Rep4Hours[]
masters: Masters[]
teams: Teams[]
filteredTeams = []
filteredMasters = []

onSelectedReport(reportId) {
  this.selectedReport = this.reports.find(
    el => {
      return el.report_id === reportId
    }
  )

  if (this.teamsService) {
    this.teamsService.fetch().subscribe(
      team => {
        this.teams = team
        this.filteredTeams = this.teams.filter(
          (team) => team.team_id == this.selectedReport.teams_id
        )
        if (this.mastersService) {
          this.mastersService.fetch().subscribe(
            master => {
              this.filteredMasters = []
              this.masters = master
              for(let team of this.filteredTeams){
                for(let master of this.masters){
                  if(master.teams_id == team.team_id){
                    if (Math.max(...this.masters.map(master => master.date_work.getTime()))) {
                      if (master.date_work <= this.selectedReport.report_date) {
                        this.filteredMasters.push(master)
                      }
                    }
                  }
                }
              }
            }
          )
        }
      }
    )
  }
}

Answer №1

In addition to xyz's response, your service has the ability to transform your "data_work" into a Date Object in JavaScript. (Assuming you received the date as a string)

//Your masterService
fetch()
{
     return this.httpClient.get(...)
     .pipe(map(x=>
           {...x,  //all the properties of "x"
            date_work:new Date(x.date_work)  //but date_work, convert to Date object 
           }
     ))
}

Answer №2

It appears that your data stored in the date_work field is not in the correct Date format. TypeScript may not be able to ensure the accuracy of the incoming service object.

There seem to be discrepancies between your model and the object returned by the service. Even though TypeScript annotates date_work as Date when mapping your class to the returning object, the actual data does not match this Date format.

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

ReactJS does not support merging multiple pages into one based on user button selection

My goal is to dynamically load a component based on the user's current page. List of Pages: Executables Shop In the main screen, there is a sidebar with two icons. The primary button should set the Executables Page and the second button should set ...

Tips for executing forEach on a promise?

I am currently working with a function that returns a promise of an array: async function functionReturningPromiseOfUserIDs(): Promise<string[]> My question is, can I use the forEach method on the array returned by this function? async function runF ...

Oops! The formGroup function in Angular 5 requires an instance of a FormGroup

While working with Angular 5, I encountered an error in this basic form. Here is the issue: Error Message: EditVisitanteDialogComponent.html:10 ERROR Error: formGroup expects a FormGroup instance. Please pass one in. Example: > > &l ...

Implementing interactive dropdown menus to trigger specific actions

I have modified some code I found in a tutorial on creating hoverable dropdowns from W3. Instead of the default behavior where clicking on a link takes you to another page, I want to pass a value to a function when a user clicks. Below is a snippet of the ...

React array fails to update upon modification

Hey there! I've created a component that takes an array of strings, combines them, and then renders a typing animation by wrapping each character in a span tag with toggling opacity from 0 to 1. I noticed an issue when switching the order of displaye ...

Mapping angular URLs with routes for the initial loading process

I recently encountered an issue with my Angular project that has multiple routes, such as /category/fruit/apple. When I try to access the full URL directly like http://myserver/category/fruit/apple, it returns a 404 error. This is because there is no confi ...

Encountering an Uncaught TypeError when attempting to set properties of null with useRef

I've been working on an app that requires access to the user's device camera in order to display live video on the screen. I've managed to achieve this by utilizing a video HTML Object and setting the media stream as its srcObject. Everythin ...

I'm having trouble getting my PrimeNG Calendar component to line up correctly

::ng-deep p-calendar.calendar-control > span > input.p-inputtext { border: 1px solid black; background: #eeeeee; text-align: center !important; } The content is not properly centered. <p-calendar dateFormat="mm/dd/yy&qu ...

Is it possible to assign a variable in typescript using the interface as its type?

Here's the snippet of code I have written interface apiResult { Token: string; Result: any; } const result: apiResult = payload.Result; I am wondering about the significance of this code. Is it possible to assign a type from an interface to ...

`How can TypeScript scripts be incorporated with Electron?`

As I work on my simple electron app, I am facing an issue where I need to include a script using the following code: <script src="build/script.js"></script> In my project, I have a script.ts file that compiles to the build folder. im ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

Angular CodeMirror Line-Break function not displaying line numbers

I am currently utilizing Code Mirror from ngx-codemirror. My goal is to split the line when it fits within the width of the parent container. After searching, I found a couple of solutions that suggest using: lineWrapping: true Additionally, in the styles ...

Error message in React: "The type 'Window & typeof globalThis' does not have a property named 'ethereum'"

Encountering a problem: Issue with 'ethereum' property on type 'Window & typeof globalThis' In my React project, I'm facing an error. The following code is causing the problem: import { ethers } from 'ethers' cons ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly. The issue arises when clicking on the favorite button causes all project cards to rese ...

Gitlab runner fails to complete lint command due to timeout issue

I am facing an issue with a specific GitLab CI step that I have defined as follows: lint: stage: frontend_check only: changes: - frontend/**/* script: - cd frontend/ngapp - npm run lint - npm run prettier Whenever I run this on ...

The TypeScript compiler does not allow a 'number' type to be assigned to 0, 10, or 20, even when the number itself is 0

When testing out my code snippet on the playground for Typescript, an error appears on line 24. I discovered that the issue can be resolved by explicitly casting commands back to <IPlan[]>, but I wonder why this extra step is necessary. Property &a ...

Experimenting with a file system library function using Jest and Typescript alongside a placeholder function

When attempting to test a library function that uses the fs module, I received assistance in this question on Stack Overflow. The feedback suggested avoiding mocks for better testing, an approach I agreed with @unional. I am now facing a similar challenge ...

Angular Components unexpectedly lose background transparency when using Transparent-Background-PNG in the foreground

Hey there! I'm currently working on a landing page and I have this amazing idea to use a stunning picture of clouds with a transparent background layered over a beautiful landscape. The only problem is that when I try to implement it, the transparency ...

The query fails to retrieve results for the specified date and the beginning of the month

I have encountered an issue with my query that is supposed to fetch values between the start and end of the month. Interestingly, when a record is entered on the first day of the month, it doesn't get returned in the query result. Only records entered ...