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

Problems with Angular 14 and NGRX Selector causing complications

At my basket store, I currently have 5 items with 2 of them having an id of 4. https://i.stack.imgur.com/YIplp.png In my reducer, when I use: on(getBasket, (state, { id }) => state.filter((photo) => photo.id !== id) It works to remove the item fr ...

Select one of 2 parameters and begin typing

I recently encountered a situation where I needed to define a type with an id field (string) and an oldId field (number), but I wanted these fields to be exclusive. For example: { id: "1234", name: "foo" } { oldId: 1234, name: "b ...

In order to incorporate Bootstrap with Angular2, I had to execute a specific command

For incorporating bootstrap with angular2, I executed the following command: $ npm install --save @ng-bootstrap/ng-bootstrap The output displayed: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40212e27352c2132726d313529232 ...

Building a Dynamic Video Element in Next Js Using TypeScript

Is there a way to generate the video element in Next JS using TypeScript on-the-fly? When I attempt to create the video element with React.createElement('video'), it only returns a type of HTMLElement. However, I need it to be of type HTMLVideoEl ...

I am seeking advice on how to create an extension for a generic class in TypeScript specifically as a getter

Recently, I discovered how to create extensions in TypeScript: interface Array<T> { lastIndex(): number } Array.prototype.lastIndex = function (): number { return this.length - 1 } Now, I want to figure out how to make a getter from it. For exam ...

What is the process for obtaining the Angular.json file for my NX Workspace?

Looking to develop a fresh Angular web application within my NX Workspace, with plans to eventually convert it for iOS and Android using Capacitor. After setting up the nx monorepo, I proceeded to generate a new Angular application by running the command ...

Discover the ultimate strategy to achieve optimal performance with the wheel

How can I dynamically obtain the changing top position when a user moves their mouse over an element? I want to perform some checks whenever the user scrolls up, so I tried this code: HostListener('window:wheel', ['$event']) onWindowS ...

Error message stating 'Module not found' is displaying in the browser console

As a beginner with Angular CLI, I recently executed the following commands at the root of my Angular project. issue-management\src\webui>ng generate module pages\dashboard issue-management\src\webui>ng generate component pag ...

Troubleshooting the issue of Angular2's http withCredentials not functioning as expected

Utilizing Angular2's HTTP module, I am sending HTTP requests. Once a user logs in, the backend server creates a cookie session which is then used by the frontend to send subsequent requests. The Angular code snippet is outlined below: get(url: string ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

Utilize string variables within TypeScript's enumeration feature

Can string variables be used in enums in TypeScript? Strings can be used in enum like so: enum AllDirections { TOP = 'top', BOTTOM = 'bottom', LEFT = 'left', RIGHT = 'right', } However, trying to use variab ...

specifying a specific type in a declaration

In this scenario, my goal is to distinguish between different types when declaring a new type: type Schedule = { flag_active : boolean, } type Channel = { flag_archived : boolean } type CreateChangeLog = { from : null, to : Schedule | Channel } ty ...

Compiling TypeScript to JavaScript with Deno

Currently experimenting with Deno projects and looking for a way to transpile TypeScript into JavaScript to execute in the browser (given that TS is not supported directly). In my previous experience with NodeJS, I relied on installing the tsc compiler via ...

Error in Angular: Unable to Access Property '..' of null

Having an issue with my Angular project where I keep getting an error message saying "cannot read property of '...' of undefined" whenever I select an employee from the combo box. The '...' represents the index of the selected employee. ...

Angular2's Dynamic Forms

When attempting to incorporate FormsArray into my Project using ReactiveFormsModule, I encountered an error message stating: Cannot find control with unspecified name attribute. Is it possible to add FormsArray in template driven forms? Here is the code ...

Retrieving a string value from a child route in Angular 2

Looking to set the header title from a child route view... In the parent component: @Component({ selector: 'parent-component', template: ` <header>{{headerTitle}}</header> <router-outlet></router-outlet ...

Sending information from a component to a route in Angular2

Is it possible to transfer data from one component to another without displaying it in the URL during routing? Currently, I am passing data using route parameters like this: { path: 'edit-tags/:type/:name/:id', component: EditTagsCompon ...

Angular 13: SyntaxError Encountered: Token 'export' Not Recognized

After upgrading Angular from version 12 to 13, I encountered an error when running the app: "Uncaught SyntaxError: Unexpected token 'export'." Here are some additional details for context: In the angular.json configuration file, I had specified ...

Issue with Angular 7: In a ReactiveForm, mat-select does not allow setting a default option without using ngModel

I have a Angular 7 app where I am implementing some reactive forms. The initialization of my reactive form looks like this: private initFormConfig() { return this.formBuilder.group({ modeTransfert: [''], modeChiffrement: [' ...

Collaborate on an Angular2 codebase for both a web application and a hybrid application

I am considering creating a mobile app based on my existing Angular2 web app codebase. After researching, I have found two possible options - Ionic2 and NativeScript. Upon further investigation, it appears that both Ionic2 and NativeScript have their own ...