Having trouble converting the response into a valid TypeScript value for storage

These are the interfaces I have described:

enum ProductType {current, closed, coming}

export interface CurrentProductForCarousel {
 type_product:ProductType.current;
 offers: ProductMainInfo[]
}

export interface ProductMainInfo {
  id: number;
  disclaimer: string;
  company?: {
    registeredOfficeState?: string;
  };
  date: {
    timestamp: number;
    days: number;
    hours: number;
  };
}

I am using ngrx-store. Here is how my reducer looks like

export interface State {
 currentProductForCarousel: CurrentProductForCarousel | null;
}

export const initialState: State = {
 сurrentProductForCarousel: null,
};

export function reducer(state = initialState, action: 
pruduct.Actions): State {
 switch (action.type) {
  case pruductActions.FETCH_PRODUCTS_CURRENT_SUCCESS: {
    return {
      ...state,
      currentProductsForCarousel: action.payload,
    };
  }

This is an example of response

{"success":true, "type_prudct":"current","products":[{"id":34, "disclaimer": "text", "company":{"registeredOfficeSuburb":"West Perth"}, "date":{"timestamp":1567987198,"days":710,"hours":"14"}}]}

The question now is how can I correctly set response data with the type of my interface to store and then retrieve data from the store?

Answer №1

Your response contains a data type that does not match the enum, as it is in string format. However, you can represent it in the following way:

type ProductType = 'current' | 'closed' | 'coming';

interface Company {
    registeredOfficeSuburb: string;
}

interface ProductDate {
    timestamp: number;
    days: number;
    hours: string;
}

interface Product {
    id: number;
    disclaimer: string;
    company: Company;
    date: ProductDate;
}

interface ProductResponse {
    success: boolean;
    type_prudct: ProductType,
    products:Product[]
}

var r: ProductResponse = {
    "success": true,
    "type_prudct": "current",
    "products": [
        {
            "id": 34,
            "disclaimer": "text",
            "company": { "registeredOfficeSuburb": "West Perth" },
            "date": { "timestamp": 1567987198, "days": 710, "hours": "14" }
        }]
};

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

What is the proper way to leverage the global 'window' object within Angular?

I'm attempting to utilize the method "window["initMapCallback"]" to invoke and monitor for "initMapCallback" in a separate file. However, I am encountering an error message in the debugging console that states Query - How can I properly implement thi ...

In Typescript, an index signature parameter can only be of type 'string' or 'number'

I'm facing an issue with a generic type that defaults to string: interface EntityState<typeOfID = string> { entities: { [ id: typeOfID]: any }; } The error I receive is: An index signature parameter type must be either 'string' or ...

find all the possible combinations of elements from multiple arrays

I have a set of N arrays that contain objects with the same keys. arr[ {values:val1,names:someName},   {values:val2,names:otherName}, ] arr2[   {values:valx,names:someNamex}, {values:valy,names:otherNamey}, ] My goal is to combine all possible c ...

What are the best ways to enhance change detection efficiency in Angular?

One issue I am facing involves two components and a service. It appears that when moving from the view of a routed component to elements in different components like a matMenu and an input field, the routed component seems to refresh itself. This becomes p ...

encountering a glitch while setting up Angular Material

Following the installation of angular-material using this command npm install --save @angular/material @angular/animations @angular/cdk Encountering an error when attempting to run 'ng serve'. This is perplexing because a similar installation ...

Navigating with Angular Router: Strategies for managing routing within a submodule's router

Seeking guidance on handling a scenario where there is a router-outlet in a high-level component and another router-outlet within its sub-component. To resolve this issue, it appears necessary to place the sub-component in its own module and set up a dedi ...

Transferring the web application context to an Angular2 service

In my project, I am attempting to pass a variable named _contextPath from a Javascript evaluated variable in a JSP file located in the folder structure shown below. The goal is to make this _contextPath variable available in a Typescript Service called job ...

Guide to adding Angular 2 components to various locations in the DOM of a vanilla JavaScript webpage

Scenario: A customer is interested in creating a library of Angular 2 components that offer a technology-agnostic interface to developers. This allows developers to use plain JavaScript without needing knowledge of the internal workings of the library. Th ...

Issue with Lazy Loading in Angular 4 Universal

I recently created a new Angular CLI project to delve into server-side rendering with Angular Universal. Everything was set up and running smoothly, until I decided to implement lazy-loading for a module named 'lazy'. After implementing lazy-lo ...

Is it possible to assign a type conditionally depending on the value of a boolean?

While grappling with this issue, the title question arose in my mind: How can I handle the situation where the library function getResponse returns { a: number } for Android phones and { b: number } for iOS phones? The code snippet below initially led to ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

Connecting table checkboxes to buttons in Angular 4.x: A step-by-step guide

Exploring Angular 4.x for the first time and faced with a challenge. I have created an HTML table where each row contains a checkbox and buttons. My goal is to link the checkboxes with the buttons in such a way that when a checkbox is checked, the correspo ...

Angular2: Ensuring Sequential Execution Line by Line - A Comprehensive Guide

I have a designed an Angular2 Navbar Component that features a logout button: import { Component, OnInit } from '@angular/core'; import { LoginService } from '../login.service'; import { Router } from '@angular/router'; @Co ...

Navigable outside graphic key in AmCharts version 4

Is it possible to achieve a scrollable legend in AmCharts 4 similar to this AmCharts 3 tutorial? With the absence of legend.divId in AmCharts 4, controlling legend size seems challenging as it is all rendered as a single SVG element with limited control us ...

Switching slides in Ionic 4 with a simple button click

I want to switch slides by clicking a button on my presentation. Here is an example code snippet: <ion-slides> <ion-slide> Slide one <ion-slide> <ion-slide> Slide Two <ion-slide> </ion-slides> <butt ...

In Typescript, try/catch blocks do not capture return values

I am currently working on a function that performs database operations, with the implementation contained within a try/catch block. Here is an example: async function update({id, ...changes}): Promise<IUserResult> { try { //insert code here retu ...

The GET request in angular with spring boot does not get triggered following a successful OPTIONS call

I am currently working on incorporating login functionality using Angular and Spring Boot in my project. To guide me, I am referring to the tutorial available at . However, a challenge I am facing is that while my Angular project is hosted on localhost:420 ...

Selling beyond webpack's confines

Today I had an interesting thought and couldn't find much information on it, so I decided to share some strange cases and how I personally resolved them (if you have a better solution, please feel free to comment, but in the meantime, this might be he ...

The routing on the Angular app is malfunctioning after deployment via Azure Static App

After using ng build --prod to create the dist folder locally, I proceeded to set up a storage account in Azure and enabled "Static App." I then uploaded the contents of the dist/xxx folder to the $web folder. However, when trying to navigate to any route, ...