Converting object's date property to a new Date() in TypeScript

I am working with a CurrentWeather Model retrieved from localStorage and parsed into an object.

export interface CurrentWeather {
    LocalObservationDateTime: Date;
    Latitude: string;
    Longitude: string;
    LocationKey: string;
    LocalizedName: string;
    PrimaryPostalCode: string;
    Temperature: number;
    RealFeelTemperature: number;
    WeatherText: string;
    UvIndex: number;
    UvIndexText: string;
}
const currentWeatherData: CurrentWeather = JSON.parse(localStorage.getItem('currentWeather'));

After parsing the data, I need to extract the hours from the LocalObservationDateTime. However, I encountered an error stating "Cannot read property 'getHours' of undefined".

 var localHour = currentWeatherData.LocalObservationDateTime.getHours();

I tried using new Date() on the Date object as suggested somewhere but it did not work.

  const localDate: Date = new Date(currentWeatherData.LocalObservationDateTime);
  const localDateHour = localDate.getHours();

Answer №1

To access the values, I had to change all property names to lowercase.

export interface WeatherData {
    localObservationDateTime: Date;
    latitude: string;
    longitude: string;
    locationKey: string;
    localizedName: string;
    primaryPostalCode: string;
    temperature: number;
    realFeelTemperature: number;
    weatherText: string;
    uvIndex: number;
    uvIndexText: string;
}

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

Include a secondary .ts file in the project that will be compiled into an additional .js file and placed in the dist

Is there a simpler way to tell NX/Angular to compile the app + an extra file separately? Currently, I have been running 2 npm scripts: nx build client-extension && npm run client-extension:injector However, this method creates extra hassle and pr ...

Angular 2, the change event is not triggering when a bootstrap checkbox is clicked

Encountering an issue, the (change) function is not triggering in a specific checkbox. <input [(ngModel)]="driver.glasses" name="glasses" type="checkbox" class="make-switch" (change)="changeFunction()" data-on-color="primary" data-off-color="info"&g ...

Altering the insides of a shallow-rendered functional component with React Enzyme

I need to modify a property value within a React component for an enzyme unit test. Specifically, I want to change the ready attribute without rendering any child components using the shallow method. Below is the simplified code for the component: import ...

The Interface in TypeScript will not function properly when used on a variable (Object) that has been declared with the value returned from a function

I am currently in the process of developing an application using Ionic v3. Strangely, I am encountering issues with my interface when trying to assign a variable value returned by a function. Here is an example that works without any problems: export int ...

Declaring a subclass type in Typescript: A step-by-step guide

Would it be feasible to create something like this? export abstract class FilterBoxElement { abstract getEntities: any; } export interface FilterBoxControlSuggestions extends FilterBoxElement { getEntities: // some implementation with different pa ...

Joining various asynchronous HTTP calls is recommended

Upon initialization, I make 4 HTTP requests for data. After that, I need to load the data from the server to fill the forms based on the data model of the last 4 HTTP calls. In simpler terms, I need to subscribe to these 4 HTTP calls and ensure they do no ...

The expandable column headers in Primeng are mysteriously missing

I'm facing an issue with my expandable row in Angular2 using Primeng2, where the column headers for the expandable columns are not displaying. Below is the code snippet of my table with expandable rows: <p-dataTable [value]="activetrucks" expanda ...

Why do referees attempt to access fields directly instead of using getters and setters?

I am facing an issue with my TypeScript class implementation: class FooClass { private _Id:number=0 ; private _PrCode: number =0; public get Id(): number { return this._Id; } public set Id(id: number) { this._Idprod ...

Using Angular Material to dynamically hide columns in a table that is being created on the fly

Is there a way to hide columns in my table based on the ID value sent to the page upon opening it? While researching, I found a method for tables with dynamically generated columns in this post: https://github.com/angular/components/issues/9940. However, t ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

Custom Pipe creates a mesmerizing infinite loop effect on images (blinking)

I have some data that needs to be displayed and it looks like this: https://drive.google.com/open?id=1Od-QC4xpfXXH4UgKDPkhkB90DQMUDAhV Here is the code snippet: <ion-grid *ngFor="let item of content | sortprogram: 'month'"> <ion-it ...

The element is not defined in the Document Object Model

There are two global properties defined as: htmlContentElement htmlContentContainer These are set in the ngAfterViewInit() method: ngAfterViewInit() { this.htmlContentElement = document.getElementById("messageContent"); this.htmlContentCont ...

The process of retrieving information from an AngularFire2 function

I am facing an issue while trying to create a variable using a function from AngularFire2. The function I am using is authorizeUser(). However, when I try to assign the result of this function to this.user, the console window displays 'undefined' ...

Is there a method or alternative solution for deconstructing TypeScript types/interfaces?

Imagine a scenario where a class has multiple type parameters: class BaseClass<T extends T1, U extends U1, V extends V1, /* etc. */ > Is there a method to consolidate these type arguments in a way that allows for "spreading" or "destructuring," sim ...

What is the process for invoking a service from a component?

I'm currently facing an issue with my service that is responsible for making HTTP requests and returning responses. The problem arises when I try to display parts of the response on the screen within my component, as nothing seems to be showing up des ...

What steps can be taken to verify that observables from distinct components have been fully executed?

I am faced with a situation where multiple components on a page are utilizing observables to fetch API data. I have implemented a loading service that is responsible for displaying a loader from the time the first observable is initiated until the last one ...

Are there any means to automatically generate placeholder methods and properties for constructor dependencies in Angular?

constructor(private a:dependencyA,private b:dependencyB,private c:dependencyC){ } Here is an example of how dependencyA is structured: export class dependencyA { showPopup: boolean; defaultProperties = { showPopup: this.showPopup, }; priva ...

Error message from webpack: It appears you are missing a necessary loader to handle this specific file type

I'm struggling with building my server.ts typescript file for the backend. I have some imports, but my app is not building. Here is a snippet from my typescript file: import * as Express from 'express' import * as Session from 'expres ...

How to Properly Convert a Fetch Promise into an Observable in Ionic 5 using Typescript?

I'm in the process of transitioning my Ionic3 app to Ionic5 and currently working on integrating my http requests. I previously utilized angular/http in Ionic3, but it appears that it has been deprecated. This was how I handled observables in my code: ...

Is there a way to limit the typing of `T extends {}` so that `keyof T` is always a string?

My current mapping type has been effective in many scenarios: type WithKeyPrefix<P extends string, T extends {}> = { [K in Extract<keyof T, string> as `${P}/${K}`]: T[K]; }; However, I'm facing an issue with rejecting objects that have ...